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
sfuser12sfuser12 

how to cover execute method

Hello,
In my batch class execute method does not cover. Can anyone suggest me how to cover execute method.

/**
* Created by CS on 12-12-2018.
*/
public without sharing class opportunityTeamMemberBatch implements Database.Batchable<sObject>, Database.Stateful {
    public Map<Id, String> opportunitiesErrors;
    public Set<Id> processedOpportunityIds;
    public Integer totalSuccessRecords = 0;
    public Integer totalFailureRecords = 0;
    
    public opportunityTeamMemberBatch() {
        opportunitiesErrors = new Map<Id, String>();
        processedOpportunityIds = new Set<Id>();
    }
    
    public Database.QueryLocator start(Database.BatchableContext BC) {
        System.debug('opportunityTeamMemberBatch.start');
        
        String query = 'SELECT Id, TeamMemberRole, Opportunity.Opportunity_Team_Member_Aliases__c, OpportunityId '
            + ' FROM OpportunityTeamMember '
            + ' Where Opportunity.Opportunity_Team_Member_Aliases__c = null';
                System.debug('opportunityTeamMemberBatch.start query'+query);
        return Database.getQueryLocator(query);
    }
    
    public void execute(Database.BatchableContext BC, List<OpportunityTeamMember> opportunityTeamMembers) {
        System.debug('opportunityTeamMemberBatch.execute opportunityTeamMembers'+JSON.serialize(opportunityTeamMembers));
       
        Map<Id, OpportunityTeamMember > opportunityIdtoOpportunityTeamMembers = new Map<Id, OpportunityTeamMember>();
        for (OpportunityTeamMember opportunityTeamMember : opportunityTeamMembers) {
            opportunityTeamMember.TeamMemberRole = opportunityTeamMember.TeamMemberRole;
            opportunityIdtoOpportunityTeamMembers.put(opportunityTeamMember.OpportunityId, opportunityTeamMember);
        }
        
        if (opportunityIdtoOpportunityTeamMembers != null) {
            List<Database.SaveResult> opportunityTeamMemberResults = Database.update(opportunityIdtoOpportunityTeamMembers.values(), false);
            System.debug('opportunityTeamMemberBatch.execute opportunityTeamMemberResults:' + JSON.serialize(opportunityTeamMemberResults));
            Set<Id> processedOpportunityIds = new Set<Id>();
            Integer index = 0;
                for (Id opportunityId : opportunityIdtoOpportunityTeamMembers.keySet()) {
                    Database.SaveResult saveResult = opportunityTeamMemberResults[index++];
                    
                    if (saveResult.isSuccess()) {
                        processedOpportunityIds.add(opportunityId);
                        totalSuccessRecords++;
                        System.debug('Successfully updated opportunity IDs ' + processedOpportunityIds);
                    } else {
                        opportunitiesErrors.put(opportunityId, saveResult.getErrors()[0].getMessage());
                        System.debug('Error occurred' + opportunityId + ': ' + saveResult.getErrors()[0].getMessage());
                        totalFailureRecords++;
                    }
                    index++;
            }
        }
    }
    
    public void finish(Database.BatchableContext batchableContext) {
        System.debug('opportunityTeamMemberBatch.finish');

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        AsyncApexJob asyncApexJob = [
            Select asyncApexJob.TotalJobItems, asyncApexJob.Status, asyncApexJob.NumberOfErrors,
            asyncApexJob.JobType, asyncApexJob.JobItemsProcessed, asyncApexJob.ExtendedStatus, asyncApexJob.CreatedById,
            asyncApexJob.CompletedDate
            From AsyncApexJob asyncApexJob
            WHERE id = :batchableContext.getJobId()
        ];
        
        System.debug('opportunityTeamMemberBatch.finish Job id is' + batchableContext.getJobId());
        
        String[] toAddresses = new String[]{
            'utkarsha.up10@gmail.com'
                };
                    mail.setToAddresses(toAddresses);
        mail.setSubject('Batch Processing ' + asyncApexJob.Status);
        mail.setPlainTextBody('Total Success Records ' + totalSuccessRecords
                              + '\n Total Failure Records ' + totalFailureRecords
                              + '\n Total Batch Apex job processed:' + asyncApexJob.TotalJobItems
                              + '\n Job Item processed: ' + asyncApexJob.JobItemsProcessed
                              + '\n Failures: ' + opportunitiesErrors);
        Messaging.sendEmail(new Messaging.SingleEmailMessage []{
            mail
                });
        System.debug('opportunityTeamMemberBatch.finish mail sent successfully');
    }
}

Test class

/**
* Created by CS on 12-12-2018.
*/
@IsTest
private class opportunityTeamMemberBatchTest {
    
    @testSetup static void setup() {
        Profile profile = [SELECT Id FROM Profile WHERE Name = 'Standard User'];
        
        User user = new User();
        user.Alias = 'alias';
        user.ProfileId = profile.Id;
        user.Email = 'testMemberUser@dfsco.com';
        user.EmailEncodingKey = 'UTF-8';
        user.LanguageLocaleKey = 'en_US';
        user.LocaleSidKey = 'en_US';
        user.TimeZoneSidKey = 'America/Los_Angeles';
        user.UserName = 'testMemberUser@dfsco.com';
        user.LastName = 'testLastName';
        insert user;
        
        Account account = new Account();
        account.Name = 'Test Account';
        account.CIK__c = '1234567899';
        account.BillingStateCode = 'IL';
        account.BillingCountryCode = 'US';
        account.BillingCity = 'McLean';
        insert account;
        
        Opportunity opportunity = new Opportunity();
        opportunity.Name = 'Test Opportunity';
        opportunity.AccountId = account.Id;
        opportunity.StageName = 'Propose';
        opportunity.CloseDate = Date.today();
        opportunity.CurrencyIsoCode = 'USD';
        opportunity.LeadSource = 'Auditor';
        opportunity.Business_Line__c = 'Capital Markets';
        opportunity.Product_Type_Interests__c = 'AD Partner Product';
        insert opportunity;
        
        OpportunityTeamMember opportunityTeamMember = new OpportunityTeamMember();
        opportunityTeamMember.TeamMemberRole = 'AD Sales Team';
        opportunityTeamMember.UserId = user.Id;
        opportunityTeamMember.OpportunityId = opportunity.Id;
        insert opportunityTeamMember;
        System.debug('opportunityTeamMemberBatchTest opportunityTeamMember'+opportunityTeamMember); 
    }
    
    static testMethod void executeBatchApexTest() {
        Test.startTest();
        System.debug('executeBatchApexTest');
        opportunityTeamMemberBatch opportunityTeamMemberBatch = new opportunityTeamMemberBatch();
        Database.executeBatch(opportunityTeamMemberBatch);
        System.debug('executeBatchApexTest Database.executeBatch'+Database.executeBatch(opportunityTeamMemberBatch));
        Test.stopTest();
    }
    
    static testMethod void batchFinishMethod() {
    }
}
Raj VakatiRaj Vakati
Try this code
 
@IsTest
private class opportunityTeamMemberBatchTest {
    
    @testSetup static void setup() {
        Profile profile = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
        
        User u = new User();
        u.Alias = 'alias';
        u.ProfileId = profile.Id;
        u.Email = 'testMemberUser@dfsco.com';
        u.EmailEncodingKey = 'UTF-8';
        u.LanguageLocaleKey = 'en_US';
        u.LocaleSidKey = 'en_US';
        u.TimeZoneSidKey = 'America/Los_Angeles';
        u.UserName = 'testMemberUser@dfsco.com';
        u.LastName = 'testLastName';
        insert u;
        
        Account acc = new Account();
        acc.Name = 'Test Account';
        acc.CIK__c = '1234567899';
        acc.BillingStateCode = 'IL';
        acc.BillingCountryCode = 'US';
        acc.BillingCity = 'McLean';
        insert acc;
        
        Opportunity opp = new Opportunity();
        opp.Name = 'Test Opportunity';
        opp.AccountId = acc.Id;
        opp.StageName = 'Propose';
        opp.CloseDate = Date.today();
        opp.CurrencyIsoCode = 'USD';
        opp.LeadSource = 'Auditor';
        opp.Business_Line__c = 'Capital Markets';
		opp.Opportunity_Team_Member_Aliases__c =null ;
		opp.Product_Type_Interests__c = 'AD Partner Product';
        insert opp;
		List<OpportunityTeamMember> oppList = new List<OpportunityTeamMember>();
        for(Integer i =0 ; i<10 ; i++){
        OpportunityTeamMember oppTeam = new OpportunityTeamMember();
        oppTeam.TeamMemberRole = 'AD Sales Team';
        oppTeam.UserId = u.Id;
        oppTeam.oppTeam = opp.Id;
		oppList.add(oppTeam) ; 
    	}
		
    insert oppList ; 
	
	}
    
    static testMethod void executeBatchApexTest() {
        Test.startTest();
        opportunityTeamMemberBatch opportunityTeamMemberBatch = new opportunityTeamMemberBatch();
        Database.executeBatch(opportunityTeamMemberBatch ,200);
        Test.stopTest();
    }
    
  
}

 
sfuser12sfuser12
Thanks Raj. but it still same
sfuser12sfuser12
Here the problem is when I change query in a class to Opportunity.Opportunity_Team_Member_Aliases__c != null then its get covered
sfuser12sfuser12
I have changed it like this and now it is 95% 

/**
* Created by CS on 12-12-2018.
*/
@IsTest
private class opportunityTeamMemberBatchTest {
    
    @testSetup static void setup() {
        Profile profile = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
        
        User u = new User();
        u.Alias = 'alias';
        u.ProfileId = profile.Id;
        u.Email = 'testMemberUser@dfsco.com';
        u.EmailEncodingKey = 'UTF-8';
        u.LanguageLocaleKey = 'en_US';
        u.LocaleSidKey = 'en_US';
        u.TimeZoneSidKey = 'America/Los_Angeles';
        u.UserName = 'testMemberUser@dfsco.com';
        u.LastName = 'testLastName';
        insert u;
        
        Account acc = new Account();
        acc.Name = 'Test Account';
        acc.CIK__c = '1234567899';
        acc.BillingStateCode = 'IL';
        acc.BillingCountryCode = 'US';
        acc.BillingCity = 'McLean';
        insert acc;
        
        Opportunity opp = new Opportunity();
        opp.Name = 'Test Opportunity';
        opp.AccountId = acc.Id;
        opp.StageName = 'Propose';
        opp.CloseDate = Date.today();
        opp.CurrencyIsoCode = 'USD';
        opp.LeadSource = 'Auditor';
        opp.Business_Line__c = 'Capital Markets';
        opp.Product_Type_Interests__c = 'AD Partner Product';
        insert opp;
        
       /* List<OpportunityTeamMember> oppList = new List<OpportunityTeamMember>();
        for(Integer i =0 ; i<10 ; i++){
            OpportunityTeamMember oppTeam = new OpportunityTeamMember();
            oppTeam.TeamMemberRole = 'AD Sales Team';
            oppTeam.UserId = u.Id;
            oppTeam.OpportunityId = opp.Id;
            oppList.add(oppTeam) ; 
        }
        
        insert oppList ; */
    } 
    
    static testMethod void executeBatchApexTest() {
        Test.startTest();
        opportunityTeamMemberBatch opportunityTeamMemberBatch = new opportunityTeamMemberBatch();
        Database.executeBatch(opportunityTeamMemberBatch ,200);
        Test.stopTest();
    }
}