function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Debendra Ray 8Debendra Ray 8 

Not able to achieve 75% Code Coverage - Urgent Response Needed

Dear All,

I'm not able to acheieve 75% code coverage for the following APEX Class :

=====================================================================
public class cvrDispController {
    
     //property
     public Customer_Visit_Report__c cvr {get; set;}
     public ListlstInvitee
     {   get;set;    }
     public ListlstAgenda  
     {   get;set;    }
     public ListlstActionPoint  
     {   get;set;    }
      
    
      // Constructor
      public cvrDispController(ApexPages.StandardSetController stdSetController){
          //stdSetController.setPageSize(10);
          cvr = new Customer_Visit_Report__c();
          lstInvitee = new List();
          lstAgenda = new List();
          lstActionPoint = new List();
            
          if(apexPages.currentPage().getParameters().containsKey('id') )
          {
            try {
                 Id cvrId = apexPages.currentPage().getParameters().get('id');
                 cvr = [select Name, Id, Date_of_Visit__c, Start_Time__c, End_Time__c, Discussion_Reference__c, Venue__c,Type__c,Account__c from Customer_Visit_Report__c where Id =:cvrId limit 1 ];
                 lstInvitee = [select Customer_Visit_Report__c, Invitee_Name__c, Id,Organization__c  from Invitee__c where Customer_Visit_Report__c =:cvrId ];
                 lstAgenda = [select Customer_Visit_Report__c, Id,Discussion_Topics__c from Agenda__c where Customer_Visit_Report__c =:cvrId ];
                 lstActionPoint = [select Customer_Visit_Report__c, Id,Action_By__c,Action_To_Be_Taken__c,BU__c,Completion_Date__c,Discusssion_Point__c,Status__c from Action_Point__c where Customer_Visit_Report__c =:cvrId  ];
            }catch (exception e) { }
          }    
      }
       
    Public Customer_Visit_Report__c getCVR(){
        
          return cvr;
    }
    
    Public List getInvitees(){
        
          return lstInvitee;
        
    }
    
    Public List getAgenda(){
        
          return lstAgenda;
       
    }
    
    Public List getActionPoint(){
        
          return lstActionPoint;
        
    }
      
}
==================================================================
Following is the correpinding Test Class :
@isTest
public class testcvrDispController {
    
    public static testMethod void testcvrController() {
        ApexPages.StandardSetController stdSetController;       
        cvrDispController controller = new cvrDispController(stdSetController);
        
         Account acc = new Account(Name='CG-UK',CurrencyIsoCode='GBP');
        insert acc;
         
        System.assertEquals(acc.Name,'CG-UK');
        System.assertEquals(acc.CurrencyIsoCode,'GBP');
        
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        User usr = new User(Alias = 'dmray', Email='dm.ray@mjunction.in',
            EmailEncodingKey='UTF-8', LastName='Ray', LanguageLocaleKey='en_US',
            LocaleSidKey='en_US', ProfileId = p.Id,
            TimeZoneSidKey='America/Los_Angeles', UserName='dm.ray@mjunction.in');
         
         insert usr;
         
         controller.cvr = new Customer_Visit_Report__c(Name='TestCVR2016-6',Account__c =acc.id ,Date_of_Visit__c=date.today(),Discussion_Reference__c='Test DR3',
                                                                  End_Time__c=date.today()+2 ,Start_Time__c=date.today()+1 ,Type__c='Existing Business',Venue__c='KOL' );
                    
        insert controller.cvr;
        
        controller.lstInvitee.add(new Invitee__c(Customer_Visit_Report__c=controller.cvr.id,Invitee_Name__c='VV',Organization__c='MJ'));
        
        insert controller.lstInvitee;
        
        controller.lstAgenda.add(new Agenda__c(Customer_Visit_Report__c=controller.cvr.id,Discussion_Topics__c='Test AGD-3'));
        
        insert controller.lstAgenda;
        
        controller.lstActionPoint.add(new Action_Point__c(Action_By__c=usr.id,Action_To_Be_Taken__c='Test-3',BU__c='MJ',Completion_Date__c=date.today()+4,
                                                          Customer_Visit_Report__c=controller.cvr.id,Discusssion_Point__c='Test DP-3',Status__c='Started'));
        
        insert controller.lstActionPoint;                    
                    
          
            if(apexPages.currentPage().getParameters().containsKey('id') ){
             
                System.debug('Info: controller.cvr.id'+ controller.cvr.Id);
                System.debug('Info: controller.lstInvitee'+ controller.lstInvitee);
                System.debug('Info: controller.lstAgenda '+ controller.lstAgenda );
                
            }
        
        Customer_Visit_Report__c cvr = controller.getCVR();
        List lstInvitee = controller.getInvitees();
        List lstAgenda = controller.getAgenda();
        List lstActionPoint = controller.getActionPoint();
        
        
        cvr.Venue__c = 'KAN';
        cvr.Id = controller.cvr.Id;
        
        upsert cvr;
        
        for(Integer j = 0;j        {
            lstInvitee[j].Invitee_Name__c = 'JJ';            
        }
        
        upsert lstInvitee;        
        
        
        for(Integer j = 0;j        {
            lstAgenda[j].Discussion_Topics__c = 'DP-1';            
        }
        
        upsert lstAgenda;          
        
        
        for(Integer j = 0;j        {
            lstActionPoint[j].Action_To_Be_Taken__c = 'FA Scrap';            
        }
        
        upsert lstActionPoint;  
                     
        
                  
        
    }


}
===========================================================================

I'll be grateful , if you could please help meachieve the minimum 75% code coverage for this APEX  Class.
An early response on this will be appreciated.

Thanks.

Regards,

Debendra Ray
Best Answer chosen by Debendra Ray 8
Amit Chaudhary 8Amit Chaudhary 8
Please try below code :-

@isTest
public class testcvrDispController 
{
    
    public static testMethod void testcvrController() 
    {
    
       Customer_Visit_Report__c cvr = new Customer_Visit_Report__c(Name='TestCVR2016-6',Account__c =acc.id ,Date_of_Visit__c=date.today(),Discussion_Reference__c='Test DR3',
                                                                  End_Time__c=date.today()+2 ,Start_Time__c=date.today()+1 ,Type__c='Existing Business',Venue__c='KOL' );
                    
        insert cvr;
     
      Test.StartTest();
      
          ApexPages.StandardController sc = new ApexPages.StandardController(cvr);
          cvrDispController testAccPlan = new cvrDispController(sc);

          PageReference pageRef = Page.AccountPlan; // Add your VF page Name here
          pageRef.getParameters().put('id', String.valueOf(cvr.Id));
          Test.setCurrentPage(pageRef);
            Customer_Visit_Report__c obj =    testAccPlan.getCVR();
            //  testAccPlan.getInvitees();
            //    testAccPlan.getAgenda();
            //    testAccPlan.getActionPoint();
                
          
     Test.StopTest();
    }

}

Please check below post of more information
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html


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 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

Please mark this as solution if this will help you

Thanks
Amit Chaudhary
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please try below code :-

@isTest
public class testcvrDispController 
{
    
    public static testMethod void testcvrController() 
    {
    
       Customer_Visit_Report__c cvr = new Customer_Visit_Report__c(Name='TestCVR2016-6',Account__c =acc.id ,Date_of_Visit__c=date.today(),Discussion_Reference__c='Test DR3',
                                                                  End_Time__c=date.today()+2 ,Start_Time__c=date.today()+1 ,Type__c='Existing Business',Venue__c='KOL' );
                    
        insert cvr;
     
      Test.StartTest();
      
          ApexPages.StandardController sc = new ApexPages.StandardController(cvr);
          cvrDispController testAccPlan = new cvrDispController(sc);

          PageReference pageRef = Page.AccountPlan; // Add your VF page Name here
          pageRef.getParameters().put('id', String.valueOf(cvr.Id));
          Test.setCurrentPage(pageRef);
            Customer_Visit_Report__c obj =    testAccPlan.getCVR();
            //  testAccPlan.getInvitees();
            //    testAccPlan.getAgenda();
            //    testAccPlan.getActionPoint();
                
          
     Test.StopTest();
    }

}

Please check below post of more information
http://amitsalesforce.blogspot.in/2015/06/best-practice-for-test-classes-sample.html


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 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

Please mark this as solution if this will help you

Thanks
Amit Chaudhary
 
This was selected as the best answer
Arunkumar RArunkumar R
Hi Debendra,

Can your try the below test class, i have not tested. Let me know if you get receive any problem,
 
@isTest
public class testcvrDispController {
    
    public static testMethod void testcvrController() 
    {
        // Mention all your required fields here.
        Customer_Visit_Report__c cvr = Customer_Visit_Report__c();
        cvr.Invitee_Name__c = 'VV';
        Organization__c = 'MJ';
        insert cvr;
        
        // Mention all your required fields here.
        Invitee__c inv = new Invitee__c();
        inv.Customer_Visit_Report__c = cvr.Id;
        inv.Invitee_Name__c = 'VV';
        inv.Organization__c = 'MJ';
        insert inv;
        
        // Mention all your required fields here.
        Agenda__c ag = new Agenda__c();
        ag.Customer_Visit_Report__c=cvr.Id;
        ag.Discussion_Topics__c='Test AGD-3';
        insert ag;
        
        // Mention all your required fields here.
        Action_Point__c ap = new Action_Point__c();
        ap.Action_By__c=Userinfo.getUserID();
        ap.Action_To_Be_Taken__c='Test-3';
        ap.BU__c='MJ';
        ap.Completion_Date__c=date.today()+4;
        ap.Customer_Visit_Report__c=cvr.Id;
        ap.Discusssion_Point__c='Test DP-3';
        ap.Status__c='Started';
        insert ap;
        
        //Mention your visualforce page name that you want to test.
        PageReference pageRef = Page.YourPageName;
        pageRef.getParameters().put('id', String.valueOf(cvr.Id));
        Test.setCurrentPage(pageRef);
        
        ApexPages.StandardController sc = new ApexPages.StandardController(cvr);
        cvrDispController cvrcontroller = new cvrDispController(sc);
        
        cvrcontroller.getCVR();
        cvrcontroller.getInvitees();
        cvrcontroller.getAgenda();
        cvrcontroller.getActionPoint();
    }
    
    
}

 
Amit Chaudhary 8Amit Chaudhary 8
Please try below code:-

@isTest
public class testcvrDispController 
{
    
    public static testMethod void testcvrController() 
    {
       Customer_Visit_Report__c cvr = new Customer_Visit_Report__c(Name='TestCVR2016-6',Account__c =acc.id ,Date_of_Visit__c=date.today(),Discussion_Reference__c='Test DR3',
                                                                  End_Time__c=date.today()+2 ,Start_Time__c=date.today()+1 ,Type__c='Existing Business',Venue__c='KOL' );
        insert cvr;

        // Mention all your required fields here.
        Invitee__c inv = new Invitee__c();
        inv.Customer_Visit_Report__c = cvr.Id;
        inv.Invitee_Name__c = 'VV';
        inv.Organization__c = 'MJ';
        insert inv;
         
        // Mention all your required fields here.
        Agenda__c ag = new Agenda__c();
        ag.Customer_Visit_Report__c=cvr.Id;
        ag.Discussion_Topics__c='Test AGD-3';
        insert ag;
         
        // Mention all your required fields here.
        Action_Point__c ap = new Action_Point__c();
        ap.Action_By__c=Userinfo.getUserID();
        ap.Action_To_Be_Taken__c='Test-3';
        ap.BU__c='MJ';
        ap.Completion_Date__c=date.today()+4;
        ap.Customer_Visit_Report__c=cvr.Id;
        ap.Discusssion_Point__c='Test DP-3';
        ap.Status__c='Started';
        insert ap;
        
      Test.StartTest();

          PageReference pageRef = Page.AccountPlan; // Add your VF page Name here
          pageRef.getParameters().put('id', String.valueOf(cvr.Id));
          Test.setCurrentPage(pageRef);

          ApexPages.StandardController sc = new ApexPages.StandardController(cvr);
          cvrDispController testAccPlan = new cvrDispController(sc);
          
            Customer_Visit_Report__c obj =    testAccPlan.getCVR();
            List lstInv = testAccPlan.getInvitees();
            List lstAge  =  testAccPlan.getAgenda();
            List lstAction=    testAccPlan.getActionPoint();
                
     Test.StopTest();
    }
}
Dave ScottDave Scott
Hi Amit, I tried your suggestion but I'm getting the error shown in the attached screenshot:

Please help!?

Many thanks,
Dave
Trigger Error
Amit Chaudhary 8Amit Chaudhary 8
Hi Please remove line number 12 } 
And try
Dave ScottDave Scott
Thanks for that Amit - that works a treat.

Also just noticed I posted this on the wrong thread, sorry for hijacking it Debendra!

Many thanks,
Dave
Debendra Ray 8Debendra Ray 8
Dear Amit, Thanks for your response – It really helped resolve my problem. Thanks & Regards, Debendra Ray Head Enterprise IT projects [cid:_2_0C3AAB780C3AA938001D1E6B65257C7F] “mjunction is in the business of solving problems whenever and wherever commerce takes place”: Mr Viresh Oberoi, CEO and MD Read the Inspiring Story of Entrepreneurial Growth of mjunction : http://www.mjunction.in/mjunctionstory …………………………………………………………… mjunction services limited Godrej Waterside, 3rd Floor, Tower 1, Plot V Block DP, Sector V, Salt Lake, Kolkata - 700091. …………………………………………………………… Landphone: +91 33 66106100 (Board) Landphone: +91 33 66106307 (Direct) Handphone: +91 85840 08270 Fax: +91 33 44091808 …………………………………………………………… Corporate Website: www.mjunction.in ……………………………………………………………
Debendra Ray 8Debendra Ray 8
Dear Arun, Thanks for your response – It helps. Thanks & Regards, Debendra Ray Head Enterprise IT projects [cid:_2_0C3AAB780C3AA938001D1E6B65257C7F] “mjunction is in the business of solving problems whenever and wherever commerce takes place”: Mr Viresh Oberoi, CEO and MD Read the Inspiring Story of Entrepreneurial Growth of mjunction : http://www.mjunction.in/mjunctionstory …………………………………………………………… mjunction services limited Godrej Waterside, 3rd Floor, Tower 1, Plot V Block DP, Sector V, Salt Lake, Kolkata - 700091. …………………………………………………………… Landphone: +91 33 66106100 (Board) Landphone: +91 33 66106307 (Direct) Handphone: +91 85840 08270 Fax: +91 33 44091808 …………………………………………………………… Corporate Website: www.mjunction.in ……………………………………………………………