+ Start a Discussion
HARSH saini 6HARSH saini 6 
trigger trigger52 on India__c (after insert) {
  list<san_francisco__c> con =new list<san_francisco__c>();  

    for(India__c h : trigger.new){
     san_francisco__c s = new san_francisco__c();
      s.Name=h.Name;
        s.Company__c=h.Company__c;
        s.Mobile__c=h.Mobile__c;
           s.Email__c=h.Email__c;
        con.add(s);
        
        
    }
    insert con;
}
Best Answer chosen by HARSH saini 6
Sitanshu TripathiSitanshu Tripathi
Dear Harsh,

I'm telling you only Way from this link.
Create Test class from yourself.

https://sitanshusfdc.blogspot.in/2018/02/apex-trigger-with-helper-class-and-test.html
StormConsultingStormConsulting 
How can I get the current Salesforce User ID in an Apex class?

Any help is appreciated!

Chris
Best Answer chosen by Admin (Salesforce Developers) 
hisrinuhisrinu
You can get the current user id like this.

UserInfo.getUserId() which returns the user id of the current user.
Chad MoutesChad Moutes 
I have an Apex Trigger that is currenty calling upon a MAX function to display the most recent date a Task has been created.
 
for(AggregateResult aggregateResult:[SELECT max(createdDate)MaxCDate,WhatId FROM Task WHERE WhatID IN: acc_set AND Status ='Completed' AND Subject ='Completed Call' Group By WhatId]){
I want to change the date field that it is referencing from createdDate to ActivityDate like below:
 
for(AggregateResult aggregateResult:[SELECT max(ActivityDate)MaxCDate,WhatId FROM Task WHERE WhatID IN: acc_set AND Status ='Completed' AND Subject ='Completed Call' Group By WhatId]){

But when I do I recieve the following error: field ActivityDate does not support aggregate operator MAX at line 26 column 42.

Can anyone help me out here?
 
Best Answer chosen by Chad Moutes
pconpcon
Unfortunately, it appears that ActivityDate is not supported for these type of operations.  There is an idea on the ideaexchange [1] dealing with this that is "partially delivered" but probably doesn't cover this.  That means you're going to have to do it manually, or do something like
 
List<Account> accounts = [
    select (
        select ActivityDate
        from Tasks
        where Status = 'Completed' and
            Subject = 'Completed Call' and
        order by ActivityDate desc
        limit 1
    )
    from Account
    where Id in :acc_set
];

And then iterate over those accounts to get the highest activity date.

[1] https://success.salesforce.com/ideaView?id=08730000000BqfzAAC
Robert Davis 16Robert Davis 16 
I have a trigger that executes on after insert and after create on the Opportunity that updates fields on the OpportunityLineItem Object. Code works but the test class opportunity does not appear to successfully add a product so the code can not go into a IF statement. I am sure this is something simple but dang if I can figure it out. Your help would be greatly appreciated:
 
TRIGGER

//Case Number 1381 - Provides information about request for Trigger
trigger UpdateOTRev on Opportunity (after insert, after update) {
    Set<id> triggerIds = new Set<id>();
    List<OpportunityLineItem> lstOLIUpdate = new List<OpportunityLineItem>();
    //See if Trigger has only been run once
    if(RecursiveTriggerHandler.isFirstTime){
        RecursiveTriggerHandler.isFirstTime = false;
         //Put all trigger opp ids into a set
         for(Opportunity Opps : Trigger.new){
            triggerIds.add(Opps.Id);
         }//END for (Opportunity Opps)
         //Get all the Opp and Products
         List<Opportunity> lstOpps = [SELECT id, CloseDate, (SELECT id, TotalPrice, One_Time_Revenue__c FROM OpportunityLineItems) FROM Opportunity 
                                      WHERE id in: triggerIds];
             //Loop through Opps
             for(Opportunity opp: lstOpps){
                 //Loop through Products in Opps
                 for(OpportunityLineItem oli : opp.OpportunityLineItems){
                     if(oli.One_Time_Revenue__c == true){
                        //Apply the logic of which fields to update
                        if(opp.CloseDate > Date.valueOf('2017-12-31') && opp.CloseDate < Date.valueOf('2018-04-01')){
                            oli.One_Time_Rev_Q1_2018__c = oli.TotalPrice;
                            oli.One_Time_Rev_Q2_2018__c = 0;
                            oli.One_Time_Rev_Q3_2018__c = 0;
                            oli.One_Time_Rev_Q4_2018__c = 0;
                            oli.One_Time_Rev_Q1_2019__c = 0;
                            oli.One_Time_Rev_Q2_2019__c = 0;
                            oli.One_Time_Rev_Q3_2019__c = 0;
                            oli.One_Time_Rev_Q4_2019__c = 0;
                            lstOLIUpdate.add(oli);              
                        }//END if 2018 Q1
                        if(opp.CloseDate > Date.valueOf('2018-03-31') && opp.CloseDate < Date.valueOf('2018-07-01')){
                            oli.One_Time_Rev_Q1_2018__c = 0;
                            oli.One_Time_Rev_Q2_2018__c = oli.TotalPrice;
                            oli.One_Time_Rev_Q3_2018__c = 0;
                            oli.One_Time_Rev_Q4_2018__c = 0;
                            oli.One_Time_Rev_Q1_2019__c = 0;
                            oli.One_Time_Rev_Q2_2019__c = 0;
                            oli.One_Time_Rev_Q3_2019__c = 0;
                            oli.One_Time_Rev_Q4_2019__c = 0;
                            lstOLIUpdate.add(oli);              
                        }//END if 2018 Q2
                        if(opp.CloseDate > Date.valueOf('2018-06-30') && opp.CloseDate < Date.valueOf('2018-10-01')){
                            oli.One_Time_Rev_Q1_2018__c = 0;
                            oli.One_Time_Rev_Q2_2018__c = 0;
                            oli.One_Time_Rev_Q3_2018__c = oli.TotalPrice;
                            oli.One_Time_Rev_Q4_2018__c = 0;
                            oli.One_Time_Rev_Q1_2019__c = 0;
                            oli.One_Time_Rev_Q2_2019__c = 0;
                            oli.One_Time_Rev_Q3_2019__c = 0;
                            oli.One_Time_Rev_Q4_2019__c = 0;
                            lstOLIUpdate.add(oli);              
                        }//END if 2018 Q3
                        if(opp.CloseDate > Date.valueOf('2018-09-30') && opp.CloseDate < Date.valueOf('2019-01-01')){
                            oli.One_Time_Rev_Q1_2018__c = 0;
                            oli.One_Time_Rev_Q2_2018__c = 0;
                            oli.One_Time_Rev_Q3_2018__c = 0;
                            oli.One_Time_Rev_Q4_2018__c = oli.TotalPrice;
                            oli.One_Time_Rev_Q1_2019__c = 0;
                            oli.One_Time_Rev_Q2_2019__c = 0;
                            oli.One_Time_Rev_Q3_2019__c = 0;
                            oli.One_Time_Rev_Q4_2019__c = 0;
                            lstOLIUpdate.add(oli);              
                        }//END if 2018 Q4
                        if(opp.CloseDate > Date.valueOf('2018-12-31') && opp.CloseDate < Date.valueOf('2019-04-01')){
                            oli.One_Time_Rev_Q1_2018__c = 0;
                            oli.One_Time_Rev_Q2_2018__c = 0;
                            oli.One_Time_Rev_Q3_2018__c = 0;
                            oli.One_Time_Rev_Q4_2018__c = 0;
                            oli.One_Time_Rev_Q1_2019__c = oli.TotalPrice;
                            oli.One_Time_Rev_Q2_2019__c = 0;
                            oli.One_Time_Rev_Q3_2019__c = 0;
                            oli.One_Time_Rev_Q4_2019__c = 0;
                            lstOLIUpdate.add(oli);              
                        }//END if 2018 Q1
                        if(opp.CloseDate > Date.valueOf('2019-03-31') && opp.CloseDate < Date.valueOf('2019-07-01')){
                            oli.One_Time_Rev_Q1_2018__c = 0;
                            oli.One_Time_Rev_Q2_2018__c = 0;
                            oli.One_Time_Rev_Q3_2018__c = 0;
                            oli.One_Time_Rev_Q4_2018__c = 0;
                            oli.One_Time_Rev_Q1_2019__c = 0;
                            oli.One_Time_Rev_Q2_2019__c = oli.TotalPrice;
                            oli.One_Time_Rev_Q3_2019__c = 0;
                            oli.One_Time_Rev_Q4_2019__c = 0;
                            lstOLIUpdate.add(oli);              
                        }//END if 2019 Q2
                        if(opp.CloseDate > Date.valueOf('2019-06-30') && opp.CloseDate < Date.valueOf('2019-10-01')){
                            oli.One_Time_Rev_Q1_2018__c = 0;
                            oli.One_Time_Rev_Q2_2018__c = 0;
                            oli.One_Time_Rev_Q3_2018__c = 0;
                            oli.One_Time_Rev_Q4_2018__c = 0;
                            oli.One_Time_Rev_Q1_2019__c = 0;
                            oli.One_Time_Rev_Q2_2019__c = 0;
                            oli.One_Time_Rev_Q3_2019__c = oli.TotalPrice;
                            oli.One_Time_Rev_Q4_2019__c = 0;
                            lstOLIUpdate.add(oli);              
                        }//END if 2019 Q3
                        if(opp.CloseDate > Date.valueOf('2019-09-30') && opp.CloseDate < Date.valueOf('2020-01-01')){
                            oli.One_Time_Rev_Q1_2018__c = 0;
                            oli.One_Time_Rev_Q2_2018__c = 0;
                            oli.One_Time_Rev_Q3_2018__c = 0;
                            oli.One_Time_Rev_Q4_2018__c = 0;
                            oli.One_Time_Rev_Q1_2019__c = 0;
                            oli.One_Time_Rev_Q2_2019__c = 0;
                            oli.One_Time_Rev_Q3_2019__c = 0;
                            oli.One_Time_Rev_Q4_2019__c = oli.TotalPrice;
                            lstOLIUpdate.add(oli);              
                        }//END if 2019 Q4
                        if(opp.CloseDate > Date.valueOf('2019-12-31')){
                            oli.One_Time_Rev_Q1_2018__c = 0;
                            oli.One_Time_Rev_Q2_2018__c = 0;
                            oli.One_Time_Rev_Q3_2018__c = 0;
                            oli.One_Time_Rev_Q4_2018__c = 0;
                            oli.One_Time_Rev_Q1_2019__c = 0;
                            oli.One_Time_Rev_Q2_2019__c = 0;
                            oli.One_Time_Rev_Q3_2019__c = 0;
                            oli.One_Time_Rev_Q4_2019__c = 0;
                            
                            lstOLIUpdate.add(oli);
                        }
                         
                     }//END if(oli.One_Time_Revenue__c == true)                     
                 }//END For(OpportunityLineItem)
             }//END for(Opportunity)
    //Update Products if there are any to update
    if(lstOLIUpdate.size()>0){
        update lstOLIUpdate;
    }
    }//END if(RecusiveTriggerHandler.isFirstTime)
}//END Class

TEST CLASS
@isTest
public class UpdateOTRevTest {
    
    public static testMethod void testOppOneTimeRevenue(){
        
        Product2 prod2= new Product2(Name = 'Test Product - OneTime',
                                     Product_Gross_Margin__c = 10,
                                     Delivery_Market__c = 'none' ,
                                     Delivery_Region__c = 'ABCD',
                                     Delivery_Site__c = 'none' ,
                                     Family = 'XTCD',
                                     Description = 'Test Product',
                                     IsActive = true,
                                     Project_Seat_Count__c = 'false',
                                     One_Time_Revenue__c = true);
        insert prod2;
        Id pricebookId = Test.getStandardPricebookId();
        PricebookEntry pbEntry = new PricebookEntry(Pricebook2Id = pricebookId,
                                                    product2Id = prod2.Id,
                                                    isActive = true,
                                                    UnitPrice = 1000);
        insert pbEntry;
       
        Opportunity opp = new Opportunity(Name = 'Test Account - Opportunity',
                                          StageName = '1 - Prospect',
                                          Type = 'New Logo', 
                                          CloseDate = System.Date.today(),
                                          LeadSource = 'BDD/AM/OPS Development',
                                          Referral_Channel__c = 'None',
                                          Auto_Generate_Quarterly_Forecast__c = 'Yes',
                                          Contract_Length_Months__c = 24,
                                          Pricebook2Id = pricebookId,
                                          Amount = 10000000);
        insert opp;
       
        OpportunityLineItem oli = new OpportunityLineItem(OpportunityId = opp.id,
                                                          PricebookEntryId = pbEntry.id,
                                                          Product2Id = prod2.id,
                                                          Quantity = 10, 
                                                          Unit_Price2__c = 20,
                                                          Adjusted_Gross_Margin_Percentage__c = 10,
                                                          Service_Channel__c = 'WIDGET',
                                                          Service_Type__c = 'Care',
                                                          One_Time_Revenue__c = true);
        insert oli;
        
        System.debug('Opportunity Product Total Price '+ oli.TotalPrice);
        System.debug('OpportunityLineItem Id ' +oli.Id);
        System.debug('Product 2 Id '+ oli.Product2Id);
        System.debug('Opportunity Line Item Name : '+ oli.Name);
        System.debug('One Time Revenue : '+oli.One_Time_Revenue__c);
        Date closeDate = System.today();
        opp.CloseDate = Date.newInstance(2018, 01, 25);
       
        update opp;
        System.debug('Opp Close Date : '+opp.CloseDate);
    }//END Method
}//END Class

//https://salesforce.stackexchange.com/questions/72883/how-to-create-opportunity-line-items-in-test-classes

Code coverage is 10 of 103 lines because it does not appear that the OpportunityLineItem ever gets associated with the Opportunity.
User-added image

I would greatly appreciate any help.

Thank you. ​
Best Answer chosen by Robert Davis 16
Robert Davis 16Robert Davis 16
This issue was the recursion class that was preventing the recursion in the class. What I ended up doing is before the Update portion of the trigger I set the RecursiveTriggerHandler.isFirstTime = true; This fixed the issue.
Clinton HatcherClinton Hatcher 
Hi all, i am new to this so thanks in advance for help. I am struggling to create a test class for my Invocable Method. I just cant get it to work - i keep getting the error Method Does not exist Or incorrect Signature. I know i am doing something wrong. Below is the two classes - 
 
public class PrevetActive4 {

    
@InvocableMethod(label='Get Prevett and update MATT' description='Returns the list of Prevett names corresponding to the specified account IDs.')
  
    public static void getPrevett2(List<Id> Ids) {

       
        List<Prevet_Checklist__c> mt = [Select Name, id,Active_Prevett__c, Open_Closed__c FROM Prevet_Checklist__c WHERE Id in :Ids AND Open_Closed__c = 'Queue' AND OwnerId = '00528000000kb5s' Order by CreatedDate ASC Limit 1];
       
        for (Prevet_Checklist__c one1 : mt) {
            one1.Open_Closed__c = 'Ready';
            one1.Active_Prevett__c = true;
            
            
        }
        update mt ;

}
}
 
@IsTest
private class TEST_Prevett2

{
    private static testMethod void myPrevettTest2() 
    {

     
       Prevet_Checklist__c PV = new Prevet_Checklist__c(Open_Closed__c = 'Queue', Active_Prevett__c = False, OwnerId = '00528000000kb5s');

       Insert PV;
        
       
       PrevetActive4.getPrevett2(PV);

    
       Prevet_Checklist__c result = [Select ID, OwnerId, Open_Closed__c, Name, Active_Prevett__c, Client_Name__c, Name_of_Adviser__c From Prevet_Checklist__c WHERE Open_Closed__c = 'Ready' AND OwnerId = '00528000000kb5s' Order by CreatedDate ASC Limit 1];
       System.assertEquals('Ready', result.Open_Closed__c);
       System.assertEquals(True, result.Active_Prevett__c);



    }
}



Thanks
 
Best Answer chosen by Clinton Hatcher
shailesh rawte 1shailesh rawte 1
Hi Clinton Hatcher,


In getPrevett2 method you declare list of id as parameter.
But in test class your passing object only.
so just add id into list and pass it from test class.
refer following code after Insert.

List<id> listid=new list<id>();
listid.add(PV.id);
PrevetActive4.getPrevett2(listid);



Thanks & Regards
Shailesh Rawte
 
Eric Anderson 54Eric Anderson 54 
Hi there,

I have two custom objects. The Investigation__c is the parent object, and the Time_Entry_Recap_Report__c is the child object. What I want to have happen is when the parent record (Investigation) is initially created, I want to create an initial entry in the 'Time_Entry_Recap_Report__c' with 15 minutes of time worked and a description of the task being 'Opened new investigation'. I'm trying to figure out how to relate the Child record to the parent record when I create the entry in the trigger. The object 'Time_Entry_Recap_Report__c' is already defined as a child to the parent, but trying to insert the record without a reference to the 'Investigation_Time_Entry__c' field within the 'Time_Entry_Recap_Report__c' object didn't work either. The Error I am getting is "Error: Compile Error: Illegal assignment from Schema.SObjectField to Id at line 8 column 7. Any assistance would be greatly appreicated. 
trigger CreateTimeEntry on Investigation__c (after insert) {
    List<Time_Entry_Recap_Report__c> entryList = new List<Time_Entry_Recap_Report__c>();
    for(Investigation__c InvestigationObj : Trigger.new){
    Time_Entry_Recap_Report__c entry = new Time_Entry_Recap_Report__c();
      entry.Hours_Worked__c = '00';
      entry.Minutes_Worked__c = '15';
      entry.Work_Performed__c = 'Opened new investigation';
      entry.Investigation_Time_Entry__c = Investigation__c.NAME;
      entryList.add(entry);
     }
     if(entryList.size()>0){
      upsert entryList;
     }
}

 
Best Answer chosen by Eric Anderson 54
Prashant Pandey07Prashant Pandey07
Hi Eric,

As @Varaprasad suggested that use the id instead of Name..name is not a valid type for the ID.. and don't use upsert because you are executing trigger only on Insert.. I have modified the code that may help you..
 
trigger CreateTimeEntry on Investigation__c (After Insert) {

     set<id>ids=new set<id>();
    
    for(Investigation__c InvestigationObj : Trigger.new){
            ids.add(InvestigationObj.id)    
     }
    Investigation__c vi=[select id,Name from Investigation__c where id=:ids limit 1]; 
             Time_Entry_Recap_Report__c stc=new Time_Entry_Recap_Report__c();
             stc.Time_Entry_Recap_Report__c=vi.id;
      try{
            if(stc.size()>0){
             insert stc;
            }
     }
     
         catch(Exception e){
      //your Exception 
     }

Thanks,
Prashant
 
Sandrine94748Sandrine94748 
Hello,

I have following error:
System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

My usecase:
I am calling a webservice in a future handler. 

Other workaround i tried:
I tried to call the webservice without a future handler, but as i am calling in trigger it is giving me error.

Can someone please tell me any workaroud ?

thank you
Best Answer chosen by Sandrine94748
mukesh guptamukesh gupta
Hi Kiran,

Please follow below code:- 
trigger descriptionUpdater on Account (after insert) {

  System.debug('Making future call to update account');
  for (Account acc : Trigger.New) {
    //Call future method to update account
    //with data from external server.
    //This is a async calls, it returns right away, after
    //enqueuing the request.

    AccountUpdater.updateAccount(acc.Id, acc.Name);
  }

}
 
public class AccountUpdater {

  //Future annotation to mark the method as async.
  @Future(callout=true)
  public static void updateAccount(String id, String name) {

    //construct an HTTP request
    HttpRequest req = new HttpRequest();
    req.setEndpoint('http://cheenath.com/tutorial/sfdc/sample1/data.txt');
    req.setMethod('GET');

    //send the request
    Http http = new Http();
    HttpResponse res = http.send(req);

    //check the response
    if (res.getStatusCode() == 200) {

      //update account
      Account acc = new Account(Id=id);
      acc.Description = res.getBody();
      update acc;
    } else {
      System.debug('Callout failed: ' + res);
    } 
  }
}

Kindly mark my solution as the best answer if it helps you.


Regards
Mukesh
 
Manoj Goswami 5Manoj Goswami 5 
Apex: 
<apex:page controller="allObjectListClass">
    <apex:pageBlock>
        <apex:form id = "myForm">
            
            <apex:pageBlockSection>
                <apex:selectList id="objList" value="{!selectedObj}" size="1">
                    <apex:selectOptions value="{!objName}"/>
                    <apex:actionSupport event="onchange" reRender="myForm"/>
                </apex:selectList>  
            </apex:pageBlockSection>
            
            <apex:pageBlockSection>
                <apex:pageblockTable value="{!fieldName}" var="f">
                    <apex:column value="{!f}"/>
                </apex:pageblockTable>
            </apex:pageBlockSection>
            
        </apex:form>        
    </apex:pageBlock>    
</apex:page>
Controller :
public class allObjectListClass {
    public String selectedObj {get;set;}
    
    public static List<selectOption> getObjName(){
        List<selectOption> options = new List<selectOption>();
        
        for ( Schema.SObjectType o : Schema.getGlobalDescribe().values() )
        {
            Schema.DescribeSObjectResult objResult = o.getDescribe();           
            system.debug( 'Sobject API Name: ' + objResult.getName() +' Sobject Label Name: ' + objResult.getLabel());           
            options.add(new SelectOption(objResult.getName(),objResult.getLabel()));
        }
        return options;
    }
    
    public static List<String> getFieldName(){
        List<String> reqFields = new List<String>();
        /*
			Required Code 
		*/
        return reqFields;
    }
}
I am getting a hard time dealing with schema methods, i have gone through the Salesforce documentation though.
Thanks in advance...


 
Best Answer chosen by Manoj Goswami 5
Prashant Pandey07Prashant Pandey07
Hi Manoj,

You can execute below code..you will get all the required field from the object.

I made selectedObj as a static variable so that we can access in your static method. 

Please mark this as a best answer if you this class helps you to solve your problem


 
public class allObjectListClass {
public static String selectedObj{get;set;}

    public static List<selectOption> getObjName(){
  
       List<selectOption> options = new List<selectOption>();
        for ( Schema.SObjectType o : Schema.getGlobalDescribe().values() )
        {
           Schema.DescribeSObjectResult objResult = o.getDescribe();           
           system.debug( 'Sobject API Name: ' + objResult.getName() +' Sobject Label Name: ' + objResult.getLabel());           
           options.add(new SelectOption(objResult.getName(),objResult.getLabel()));
         
        }
        return options;
    }

    
    public static List<String> getFieldName(){
     List<String> reqFields = new List<String>();
           if(selectedObj!=null){
        system.debug('^^^^^^'+selectedObj );
    
        Map <String,Schema.SObjectType> gd = Schema.getGlobalDescribe();
        Schema.SObjectType sobjType = gd.get(selectedObj);
        Schema.DescribeSObjectResult r = sobjType.getDescribe();
        Map<String, Schema.SObjectField> MapofField = r.fields.getMap();
                       for(String fieldName : MapofField.keySet()) {
                        Schema.SObjectField field = MapofField .get(fieldName);
                        Schema.DescribeFieldResult F = field.getDescribe();
        if( F.isCreateable() && !F.isNillable() && !F.isDefaultedOnCreate() )
        {
       reqFields.add(fieldName );
        }
       }

    }
    return reqFields;    
}

}


<!--************Visualfroce***********-->

<apex:page controller="allObjectListClass">
   <apex:pageBlock >
        <apex:form id="myForm">
            
            <apex:pageBlockSection >
                <apex:selectList id="objList" value="{!selectedObj}" size="1">
                    <apex:selectOptions value="{!objName}"/>
                    <apex:actionSupport event="onchange" reRender="myForm"/>
                </apex:selectList>  
            </apex:pageBlockSection>
            
            <apex:pageBlockSection >
                <apex:pageblockTable value="{!fieldName}" var="f">
                    <apex:column value="{!f}"/>
                </apex:pageblockTable>
            </apex:pageBlockSection>
            
        </apex:form>        
    </apex:pageBlock>   
</apex:page>

 
Chris PulliamChris Pulliam 
<apex:page id="Page" showHeader="false" controller="MyCustomVFPage_CTR" action="{!InitPage}" cache="false">
    <apex:form >
        Thank you for your response.
    </apex:form>
</apex:page>
^ Visualforce page. When someone clicks a link in an alert email I sent them it directs them here, and appends a value in the url based on what link in the alert they click: accepted or rejected. 
 
public class MyCustomVFPage_CTR {
    public String ObjectId {get;set;}
    public String ResponseCode {get;set;}
    public MyCustomVFPage_CTR () {
        ObjectId = ApexPages.currentPage().getParameters().get('ObjectId');
        ResponseCode = ApexPages.currentPage().getParameters().get('ResponseCode');
    }
    public PageReference InitPage() {
        List<Lead> CustomerIssues = [SELECT Id, Status FROM Lead WHERE Id=:ObjectId LIMIT 1];
        if(!CustomerIssues.IsEmpty()){
            CustomerIssues[0].Status = ResponseCode;
            UPDATE CustomerIssues;
        }
        Return null;
    }
}
^ class takes the value that's passed from the url, and updates the related record.

I don't know how to get code coverage for that class. Do I need to write something to test going to a visualforce page?





 
Best Answer chosen by Chris Pulliam
Amit Chaudhary 8Amit Chaudhary 8
Please check below post to learn about test classes
1) http://amitsalesforce.blogspot.com/search/label/Test%20Class
2) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Please try below test class.
@isTest 
public class MyCustomVFPage_CTRTest 
{
	static testMethod void testMethod1() 
	{

		Lead lead=new Lead(LastName='Doe',FirstName='John',Company='Test',Status='Converted');
		insert lead;  

		
		Test.StartTest(); 
		
			PageReference pageRef = Page.MyCustomVFPage; // Add your VF page Name here
			pageRef.getParameters().put('ResponseCode', 'Test');
			pageRef.getParameters().put('ObjectId', String.valueOf(lead.Id));
			Test.setCurrentPage(pageRef);
			
			MyCustomVFPage_CTR obj = new MyCustomVFPage_CTR();

			obj.InitPage(); 
			
		Test.StopTest();
	}
}

Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .


Please let us know if this post will help you

Thanks,
Amit Chaudhary
Lakshmi SLakshmi S 
Hi All,

Q). What is a future method ? When we are going to use Future methods? Example program for Future method and Schedulable class for Future method?

Give me reply anyone.....
Best Answer chosen by Lakshmi S
NagendraNagendra (Salesforce Developers) 
Hi Lakshmi Narasimha,

What is Future Method:

A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you'd like to run in its own thread, on its own time.

When to use Future Method:

If you want to make the execution of the apex program to run asynchronously then we make use of future method.When you specify
future , the method executes when Salesforce has available resources. For example, you can use the future annotation when making an asynchronous Web service callout to an external service.

Apex class with Future Method:
public class AccountProcessor 
{
  @future
  public static void countContacts(Set<id> setId) 
  {
      List<Account> lstAccount = [select id,Number_of_Contacts__c , (select id from contacts ) from account where id in :setId ];
      for( Account acc : lstAccount )
      {
          List<Contact> lstCont = acc.contacts ;
          
          acc.Number_of_Contacts__c = lstCont.size();
      }
      update lstAccount;
  }
}

Test class for the above:
@IsTest
public class AccountProcessorTest {
    public static testmethod void TestAccountProcessorTest() 
    {
        Account a = new Account();
        a.Name = 'Test Account';
        Insert a;

        Contact cont = New Contact();
        cont.FirstName ='Bob';
        cont.LastName ='Masters';
        cont.AccountId = a.Id;
        Insert cont;
        
        set<Id> setAccId = new Set<ID>();
        setAccId.add(a.id);
 
        Test.startTest();
            AccountProcessor.countContacts(setAccId);
        Test.stopTest();
        
        Account ACC = [select Number_of_Contacts__c from Account where id = :a.id LIMIT 1];
        System.assertEquals ( Integer.valueOf(ACC.Number_of_Contacts__c) ,1);
  }
  
}

Instead of a Schedulable class, try using a batch class. batch classes can be scheduled using the UI, and can call @future methods.
global class ScheduledDispatcher Implements Schedulable{

    public Interface IScheduleDispached{
        void execute(SchedulableContext sc);
    }

    global void execute(SchedulableContext sc){
        Type targetType = Type.forName('{HANDLERNAME');
        if(targetType != null){
            IScheduleDispached obj = (IScheduleDispached)targetType.newInstance();
            obj.execute(sc);
        }
    }


}

public class {HANDLERNAME} implements ScheduledDispatcher.IScheduleDispached {

  public void execute(SchedulableContext sc)
    {

        //Call your Future Method Here

    } 

}
For more information refer to the below link.
http://amitsalesforce.blogspot.sg/2015/02/future-methods-in-salesforce.html

Kindly mark my solution as the best answer if it helps you.

Best Regards,
Nagendra.P