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
subodh chaturvedi 17subodh chaturvedi 17 

how to write the test class of this batch class where Child Object is Solution_participation__c & parent is account

global class BatchPopulateSolutionInventory implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
           String soqlQuery = 'select id,Solution_Participation_Category__c from Account';  
           return Database.getQueryLocator(soqlQuery);
    }

    global void execute(Database.BatchableContext BC, List<Account> scope) {    
            /*for(Account a:scope){
                accSet.add(a.Id);
            }*/
            set<String> uniqueSol_Name= new set<String>();
            map<Id, set<String>> mapTest = new map<Id, set<String>>();
            list<account> accupdate = new list<Account>();
            set<Id> accIds = new set<Id>();
            list<Solution_Participation__c> test =[select Id, Solution_Name__c,Account__c from Solution_Participation__c 
                                                  where 
                                                  Account__c IN :scope];
                                                  
            for(Account acc:scope) {          
             
                for(Solution_Participation__c Sol : test) {
                    
                    if(Sol.solution_name__c != null && Sol.Account__c == acc.Id) {
                        uniqueSol_Name.add(Sol.solution_name__c);
                        accIds.add(Sol.Account__c);
                    }                          
                }
                if(accIds.contains(acc.Id)) {
                    mapTest.put(acc.Id, uniqueSol_Name);    
                }           
            }
            system.debug('**mapTest**'+mapTest);
            for(Account acc:scope) {
                string testStr = '';
                boolean flag = true;
                if(mapTest.containskey(acc.Id))
                for(String strObj : mapTest.get(acc.Id)) {
                    if(flag) {
                        testStr = strObj;
                        flag = false;
                    }
                    else {
                        testStr = testStr+';'+strObj;
                    }
                }
                acc.Solution_Participation_Category__c = testStr;
                accupdate.add(acc);
            }
            if(accupdate.size() >0) {
                update accupdate;
            }
     } 
    global void finish(Database.BatchableContext BC){}
}
Best Answer chosen by subodh chaturvedi 17
v varaprasadv varaprasad
Hi Subodh,

Please check once below code : 
@isTest
public class BatchPopulateSolutionInventory_Test {

    /*
* MethodName     : testData
* Description    : Create Testdata in @testSetup, use same data in all testmethods of this class.
*/
    @testsetup
    public static void testData(){
        list<account> lstAccs = new list<account>();
        list<Solution_Participation__c> lstCons = new list<Solution_Participation__c>();
    
        //Sample test data inserting here:
        for(integer i =0; i<10;i++){
            Account accData = new Account(
                name = 'testAcc'+i,
                Solution_Participation_Category__c  = 'Testdata' //Here give your data                    
            
            );
            lstAccs.add(accData);
        
        }
        insert lstAccs;
    
        integer i = 0;
        for(account acc : lstAccs){
            Solution_Participation__c con = new Solution_Participation__c(
                Solution_Name__c = 'testingcons'+i,               
                Account__c  = acc.id                    
            );
            i++;        
            lstCons.add(con);
        }
        insert lstCons;
    
    }

    /*
* MethodName     : methodTest
* Description    : testing class methods.
*/

    public static testmethod void BatchPopulateTest(){
        //Querey TestData
        list<account> lstAccsdata = [select id,Solution_Participation_Category__c from Account];
        ist<Solution_Participation__c> lstConsdata = [select Id, Solution_Name__c,Account__c from Solution_Participation__c 
                                                  where 
                                                  Account__c IN :lstAccs];
        //Use assert statements
        system.assertEquals(10, lstConsdata.size())
        
            //Use test.startTest() and stopTest() for refreshing governor limits.
            test.startTest();
        BatchPopulateSolutionInventory bch = new BatchPopulateSolutionInventory();
            Database.executeBatch(bch);
        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 .

Hope it helps you.


Thanks
varaprasad 

All Answers

v varaprasadv varaprasad
Hi Subodh,

Please check once below code : 
@isTest
public class BatchPopulateSolutionInventory_Test {

    /*
* MethodName     : testData
* Description    : Create Testdata in @testSetup, use same data in all testmethods of this class.
*/
    @testsetup
    public static void testData(){
        list<account> lstAccs = new list<account>();
        list<Solution_Participation__c> lstCons = new list<Solution_Participation__c>();
    
        //Sample test data inserting here:
        for(integer i =0; i<10;i++){
            Account accData = new Account(
                name = 'testAcc'+i,
                Solution_Participation_Category__c  = 'Testdata' //Here give your data                    
            
            );
            lstAccs.add(accData);
        
        }
        insert lstAccs;
    
        integer i = 0;
        for(account acc : lstAccs){
            Solution_Participation__c con = new Solution_Participation__c(
                Solution_Name__c = 'testingcons'+i,               
                Account__c  = acc.id                    
            );
            i++;        
            lstCons.add(con);
        }
        insert lstCons;
    
    }

    /*
* MethodName     : methodTest
* Description    : testing class methods.
*/

    public static testmethod void BatchPopulateTest(){
        //Querey TestData
        list<account> lstAccsdata = [select id,Solution_Participation_Category__c from Account];
        ist<Solution_Participation__c> lstConsdata = [select Id, Solution_Name__c,Account__c from Solution_Participation__c 
                                                  where 
                                                  Account__c IN :lstAccs];
        //Use assert statements
        system.assertEquals(10, lstConsdata.size())
        
            //Use test.startTest() and stopTest() for refreshing governor limits.
            test.startTest();
        BatchPopulateSolutionInventory bch = new BatchPopulateSolutionInventory();
            Database.executeBatch(bch);
        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 .

Hope it helps you.


Thanks
varaprasad 
This was selected as the best answer
subodh chaturvedi 17subodh chaturvedi 17
Hi vvaraprasad ,

I  have called this batch class in schedule class & written the test class Of schedular class but when i run the test class of schedular it is giving 100% code coverage but in batch class it is giving 12% code coverage. 

This is My schedule Class 
global with sharing class Schedule_BatchPopulateSolutionInventory implements Schedulable{
     global void execute(SchedulableContext sc) {
          // We now call the batch class to be scheduled
          BatchPopulateSolutionInventory sbpsi = new BatchPopulateSolutionInventory();
        //Parameters of ExecuteBatch(context,BatchSize)
       ID batchprocessid = database.executebatch(sbpsi,200);
     }
  }
..................................................................................................................................................................................
This is my schedule test Class 
@istest
public with sharing class TestScheduleBatchPopulateSolnInventory {
    static testmethod void testSample() {
        Test.startTest();
        Schedule_BatchPopulateSolutionInventory  obj = new Schedule_BatchPopulateSolutionInventory();
        obj.execute(null);
        Test.stopTest();
    }

}
v varaprasadv varaprasad
Hi Subodh,


Use below code in test class 
 
remove below code :

 //Use test.startTest() and stopTest() for refreshing governor limits.
            test.startTest();
        BatchPopulateSolutionInventory bch = new BatchPopulateSolutionInventory();
            Database.executeBatch(bch);
        test.stopTest();


Use below code in test class:

test.startTest();
 Schedule_BatchPopulateSolutionInventory  sh1 = new Schedule_BatchPopulateSolutionInventory ();
 String sch = '0 0 23 * * ?';
 system.schedule('Test Territory Check', sch, sh1); Test.stopTest();
test.stopTest();

So it will cover batch and schedule apex i think.

Otherwise, create two test classes for batch and schedule apex.

Thanks
Varaprasad