0

I'm new to batch scripts. In my apex batch My start method will send records to execute method based on input given in custom label. I have created a test class and I'm not sure my execute method is not getting covered.. Can anyone guide how to write test class for cover this scenario.

//My Apex class
Global class mybatch  implements Database.Batchable<sObject> {
    
    //Start Method
    Global Database.QueryLocator start(Database.BatchableContext BC){
        Id testrecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('test').getRecordTypeId();
        
        String  passID = System.Label.passID; 
        String soql = '';
        
        if(passID == 'null') {
            return DataBase.getQueryLocator([SELECT Id, Name
                                             FROM Account 
                                             WHERE RecordTypeid =:testrecordTypeId limit 0]);//no records passed to execute
        }
        else if(passID == 'All'){
            return DataBase.getQueryLocator([SELECT Id, Name
                                             FROM Account 
                                             WHERE RecordTypeid =:testrecordTypeId]);//All records are passed to execute
        }
        else {
            string mysiteID=System.Label.passID;
            list<string> mysiteslist=mysiteID.split(','); 
            
            return Database.getQueryLocator([SELECT Id, Name
                                             FROM Account 
                                             WHERE Id =:mysiteslist]);//only particular recordtypes are passed to execute
        }
    }
    // Execute method
    global void execute(Database.BatchableContext BC, List<Account> accounts) {
        try { 
            
            Integer currentyear= date.today().year();//fetch current year

            ID myuserrecordtypeid = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('myuser').getRecordTypeId();
            
            //Fetch all Contacts for Account got from Start
            list<Contact> Contactlist = new list<Contact>();//list to update contacts
            Contactlist =[select id from Contact Where AccountId=:accounts
                          AND RecordTypeId  = :myuserrecordtypeid ];
            system.debug('--ContactlistSize-->'+Contactlist.size());
            system.debug('--Contactlist-->' + Contactlist );
            
            
            for(Contact contlist : Contactlist){
                
                contlist.FirstName=Null;
                contlist.Middlename=Null;
                contlist.lastname = contlist.id + '-&'+currentyear;            
                
            }
            
            
            //Fetch and store all memberships related to the contact above
            list<Membership__c> Membershiplist = new list<Membership__c>();
            Membershiplist=[select id,Member__r.id  from Membership__c Where Member__c=:Contactlist];
            system.debug('--MembershiplistSize-->'+Membershiplist.size());
            system.debug('--Membershiplist-->'+Membershiplist );
            
            for(Membership__c Memblist : Membershiplist){
                Memblist.First_Name__c=null;
                Memblist.Last_Name__c =null;
                Memblist.Name  = Memblist.Member__r.id + '-&'+currentyear;
            }
            
            
            update Contactlist;
            update Membershiplist;
           
            
            //delete field history tracking of contact records
            list<ContactHistory> Contacthistorylist = new list<ContactHistory >();
            Contacthistorylist =[select ContactId from ContactHistory  Where ContactId=:Contactlist];
            system.debug('--ContacthistorylistSize-->'+Contacthistorylist.size());
            system.debug('--Contacthistorylist-->' + Contacthistorylist );
            
            
            //delete field history tracking of Membership records 
            list<Membership__History> Membershiphistorylist = new list<Membership__History>();
            Membershiphistorylist =[select ParentId from Membership__History  Where ParentId=:Membershiplist];
            system.debug('--MembershiphistorylistSize-->'+Membershiphistorylist.size());
            system.debug('--Membershiphistorylist-->' + Membershiphistorylist );
            
            
            
            //to delete all history records in single shot
            List<sObject> deletehistoryrecordslist = new List<sObject>();
            deletehistoryrecordslist.addAll((List<sObject>)(Contacthistorylist));
            deletehistoryrecordslist.addAll((List<sObject>)(Membershiphistorylist));
            system.debug('--deletehistoryrecordslist-->' + deletehistoryrecordslist );
            delete deletehistoryrecordslist;
            
        }catch(Exception e){
            String ExcptionMessage2=e.getMessage() +';'+ e.getLineNumber() +';'+ e.getStackTraceString();
            System.debug('--An unexpected error has occurred:-->' + e.getMessage());
        }   
    }
    //Finish Method
    Global void finish(Database.BatchableContext BC)
    {
        system.debug('--mybatch  Job Finished scuessfully-->');
    }
    
}
//My test class
@isTest
public class mytestclass {
    
    static testmethod void test() {
        
        ID testrecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Site').getRecordTypeId();
        
        Integer currentyear= date.today().year();//fetch current year
        
        Account acc = TestDataFactory.getAccount();
        acc.Name = 'Demo Account';
        INSERT acc;
        System.assertEquals('Demo Account', acc.Name);
        
        Contact con     = TestDataFactory.getContact();
        con.FirstName   = 'Demo Contact';
        con.LastName    = 'Demo Contact';
        con.AccountId   = acc.Id;
        con.Email       = '[email protected]';
        con.Phone       = '12345';
        INSERT con;
        System.assertEquals('Demo Contact', con.FirstName);
        system.assertNotEquals(con, null); 
        system.assertEquals(con.AccountId , acc.Id);
      
        list<Account> Accountlist = new list<Account>();//list to update Accounts
            Accountlist =[select id from Account ];
            system.debug('--AccountlistSize-->'+Accountlist.size());
            system.debug('--Accountlist-->' + Accountlist );
        
        list<Contact> Contactlist = new list<Contact>();//list to update contacts
            Contactlist =[select id from Contact ];
            system.debug('--ContactlistSize-->'+Contactlist.size());
            system.debug('--Contactlist-->' + Contactlist );
            
        
        Test.startTest();
        mybatch exebatch = new mybatch();
        database.executeBatch(exebatch,1);
        Test.stopTest();
         system.debug('--Contactlist'+Contactlist);
         system.debug('--Accountlist'+Accountlist);
        system.assertNotEquals(Contactlist.isEmpty(), true);

        
    }
    
}

1 Answer 1

0

This is something that you need to find out with the execution test class. few points I noticed

  1. check the record type of account record created using getAccount.
  2. there is a deference record type name refer in the test class and batch job.
  3. No data created for the membership object.
  4. you can get the unexecuted code using dev console. improve your test class according to the unexecuted codes

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .