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
Admin_dev.ax1029Admin_dev.ax1029 

Batch Apex Test Class Code Coverage

Hello Devs,

    Not sure what i have to modify in test class to make it 75% coverage , but right now it's only giving me 22%, any help is appreciated, this code can be implemented in any org since no custom fields are involved.

 

global class UpdPrimaryCampaignOnOpty implements Database.Batchable<sObject>{

    global String Query;
    global UpdPrimaryCampaignOnOpty(){
        query = 'Select Id, contactId, opportunityId,isPrimary from OpportunityContactRole where (createddate = today or lastmodifieddate = today) and  opportunity.CampaignId = null';
    }
   
   
     global DataBase.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        System.debug('scope size = '+scope.size());
        set<Id> conIds = new Set<Id>();
        Set<Id> optyIds = new Set<Id>();
        Map<Id,Id> optyConMap = new Map<Id,Id>();
        for(sObject s : scope){
            OpportunityContactRole ocr = (OpportunityContactRole)s;
            if(ocr.isPrimary){
                conIds.add(ocr.contactId);
                optyIds.add(ocr.opportunityId);
                optyConMap.put(ocr.OpportunityId, ocr.ContactId);
            }
        }
        System.debug('conIds size = '+conIds.size());
        System.debug('optyIds size = '+optyIds.size());
        System.debug('optyConMap size = '+optyConMap.size());
       
        List<CampaignMember> cmList = [Select id, CampaignId, ContactId, Campaign.createddate from CampaignMember where ContactId IN :conIds];
        System.debug('cmList size = '+cmList.size());
        Map<Id,CampaignMember> contactCampaignMap = new Map<Id,CampaignMember>();
        for(CampaignMember cm : cmList){
           
            if(contactCampaignMap.containsKey(cm.contactId) && cm.Campaign.createddate > contactCampaignMap.get(cm.contactId).Campaign.CreatedDate ){
                contactCampaignMap.put(cm.contactId, cm);
            }
            else{
                contactCampaignMap.put(cm.contactId, cm);
            }          
        }
       
        List<Opportunity> optyList = [Select Id, CampaignId from Opportunity where Id IN :optyIds];
       
        for(Opportunity opty : optyList){
            if(optyConMap.containsKey(opty.id) && contactCampaignMap.containsKey(optyConMap.get(opty.Id))){
                opty.CampaignId = contactCampaignMap.get(optyConMap.get(opty.Id)).CampaignId;
            }       
        }
       
        update optyList;
       
    }
   
    global void finish(Database.BatchableContext BC){
      
   }
        static testMethod void myUnitTest() {
        Test.StartTest();
        UpdPrimaryCampaignOnOpty upc =  new UpdPrimaryCampaignOnOpty();       
        upc.query = upc.query +'Limit 200' ;
        ID batchprocessid = Database.executeBatch(upc);
        Test.StopTest();    
   
  } 
}

Admin_dev.ax1029Admin_dev.ax1029

Hello,

    My Class is not giving enough coverage, it's only giving 22% ,not sure what else could be written , Any help is appreciated .

 

 

global class UpdPrimaryCampaignOnOpty implements Database.Batchable<sObject>{

    global String Query;
    global UpdPrimaryCampaignOnOpty(){
        query = 'Select Id, contactId, opportunityId,isPrimary from OpportunityContactRole where (createddate = today or lastmodifieddate = today) and  opportunity.CampaignId = null';
    }
   
   
     global DataBase.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        System.debug('scope size = '+scope.size());
        set<Id> conIds = new Set<Id>();
        Set<Id> optyIds = new Set<Id>();
        Map<Id,Id> optyConMap = new Map<Id,Id>();
        for(sObject s : scope){
            OpportunityContactRole ocr = (OpportunityContactRole)s;
            if(ocr.isPrimary){
                conIds.add(ocr.contactId);
                optyIds.add(ocr.opportunityId);
                optyConMap.put(ocr.OpportunityId, ocr.ContactId);
            }
        }
        System.debug('conIds size = '+conIds.size());
        System.debug('optyIds size = '+optyIds.size());
        System.debug('optyConMap size = '+optyConMap.size());
       
        List<CampaignMember> cmList = [Select id, CampaignId, ContactId, Campaign.createddate from CampaignMember where ContactId IN :conIds];
        System.debug('cmList size = '+cmList.size());
        Map<Id,CampaignMember> contactCampaignMap = new Map<Id,CampaignMember>();
        for(CampaignMember cm : cmList){
           
            if(contactCampaignMap.containsKey(cm.contactId) && cm.Campaign.createddate > contactCampaignMap.get(cm.contactId).Campaign.CreatedDate ){
                contactCampaignMap.put(cm.contactId, cm);
            }
            else{
                contactCampaignMap.put(cm.contactId, cm);
            }          
        }
       
        List<Opportunity> optyList = [Select Id, CampaignId from Opportunity where Id IN :optyIds];
       
        for(Opportunity opty : optyList){
            if(optyConMap.containsKey(opty.id) && contactCampaignMap.containsKey(optyConMap.get(opty.Id))){
                opty.CampaignId = contactCampaignMap.get(optyConMap.get(opty.Id)).CampaignId;
            }       
        }
       
        update optyList;
       
    }
   
    global void finish(Database.BatchableContext BC){
      
   }
        static testMethod void myUnitTest() {
        Test.StartTest();
        UpdPrimaryCampaignOnOpty upc =  new UpdPrimaryCampaignOnOpty();       
        upc.query = upc.query +'Limit 200' ;
        ID batchprocessid = Database.executeBatch(upc);
        Test.StopTest();    
   
  } 
}

AndyOgnenoffAndyOgnenoff

The main problem is that you're not actually testing anything.  You're executing your method without setting up any test data or asserting that your logic operates as expected. It may work fine in a sandbox where you have setup your data conditions but your unit tests should not rely on any data being the org.

 

Check out this article for examples of how to unit tests:

 

http://wiki.developerforce.com/index.php/An_Introduction_to_Apex_Code_Test_Methods

colemabcolemab

Duplicate post my dear watson.

Admin_dev.ax1029Admin_dev.ax1029

i know but iam not able to find the solution, so thought posting twice might help the people in the forum to look at this again

colemabcolemab

You probably need to read some more of the documentation to get full code coverage and real tests.    However, here is some code to get the ball rolling on a smoke test (i.e. code coverage but not actual testing).

 

static testMethod void myUnitTest() 
{

	// create our test data before testing the class

	// The first method is UpdPrimaryCampaignOnOpty which is a query
	// that will require an account, opportunity, contact, and a role
	
	// create an account
	Account MyAccount = new Account(Name='Test');
	insert MyAccount;

	// Create a Opportunity on the test account
	date myDate = date.today();
	Opportunity MyOppty = new opportunity(Name='Test',CloseDate=myDate,StageName='Lead');
	MyOppty.AccountId = MyAccount.Id;	
	insert MyOppty;

	// Create a contact
	Contact MyContact = new Contact();
	MyContact.LastName = 'Test'
	insert MyContact

	// Give the contact a role on the opportunity
	OpportunityContactRole MyRole = new OpportunityContactRole();
	MyRole.ContactId = MyContact.Id;
	MyRole.OpportunityId = MyOppty.Id;
	MyRole.Role = 'Other';
MyRole.IsPrimary = true;
insert MyRole; // logic to test the class Test.StartTest(); UpdPrimaryCampaignOnOpty upc = new UpdPrimaryCampaignOnOpty(); upc.query = upc.query +'Limit 200' ; ID batchprocessid = Database.executeBatch(upc); Test.StopTest(); }

  The changes I made give you test data for the first method you just need to write the code for the 2nd method (which is the larger of the two).

 

Hope this helps.

 

EDIT:  Here is a link for the documentation on the batch apex test methods.

Admin_dev.ax1029Admin_dev.ax1029

Hi,

  I appreciate for the reply, actually i never wrote test class for the batch apex class, i did wrote for trigger so this is totally kind of new and i did implement the code which you gave before but it's only giving me 22% and not sure what i have to do :(

colemabcolemab

My code was for a normal test cases and not for apex batch testing.

 

You need to read the documentation at this address:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_batch_interface.htm

 

It has a section at the bottom called 'Testing Batch Apex' that describes and gives examples for writing test cases for batch apex code.   

Admin_dev.ax1029Admin_dev.ax1029

Thx Again,

        I saw the documentation but it's too high level for me as Admin, not sure how to just get out from this batch apex test class :(

colemabcolemab

If you wrote the batch apex code, then writing the test method (especially with the documentation @ the link I gave) shouldn't be a big deal at all.