Test class for batch apex

Batch apex is always in rescue whenever you need to process a huge chunk of data.

Consider the following batch apex. 

The business functionality it achieves is.

Check for a change in a custom field called keywords__c in Account object and Insert that topic into a community.

/**************************************************************************

* @Name:BatchNewTopicsUpdate
* @author : Monish

public with sharing class BatchNewTopicsUpdate implements Database.Batchable<sObject>{
	
	public Database.QueryLocator start(Database.BatchableContext BC){
		
        String query = 'select id , Name , Keywords__c from account where LastModifiedDate  = YESTERDAY';
        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext BC, List<Account> accountsList){
        
        //check any accounts is there
        if(accountsList.size() != 0 || accountsList != null){
        	
        	//Get account keywords 
	        Set<String> accountKeywordsSet = new set<String>();
	        
	        for( Account accForVar : accountsList ){
	            
	            if(accForVar.Keywords__c != null ){
	                
	                String tempKeywordString = accForVar.Keywords__c.trim();
	                
	                list<String> allKeywordsList = new list<String>();
	                
	                allKeywordsList = tempKeywordString.split(',');
	                
	                if(allKeywordsList.size() > 0){
	                	for(string stringForVar : allKeywordsList){
                        
                        	accountKeywordsSet.add(stringForVar.trim());
                    	}	                	
	                }	                
	            }            
	        }
	        
	                
	        //Get all topics
	        set<String> topicSet = new set<String>();
	        list<Topic> topicList = new list<Topic>();
			topicList = [select id , Name  from Topic ];
			
			for(Topic topicForVar : topicList){
				topicSet.add(topicForVar.name);
			}
			
			//get Community id	
	        String communityId='';
	        
            if(!Test.isRunningTest()){
                ConnectApi.CommunityPage communityItem =  ConnectApi.Communities.getCommunities();
	           
                for(ConnectApi.Community ccc:communityItem.communities){                    
                   if(ccc.Id!=null || ccc.Id !=''){                    
                    communityId =ccc.Id;
                   }           
                }
            }
			
			//compare account keywords present in topics else add it in 
			
			list<String> newTopics = new list<String>();
			
			list<Topic> topicListToInsert = new list<Topic>();
			
			for(string keywordForVar : accountKeywordsSet){
				
				if(!topicSet.contains(keywordForVar)){
					
					Topic newTopicTemp = new Topic();
					newTopicTemp.name = keywordForVar;
					newTopicTemp.NetworkId = communityId;
					
					if(newTopicTemp.Name != null && newTopicTemp.Name !='' && keywordForVar.length() <= 99){
						topicListToInsert.add(newTopicTemp);
					}			
				}
			}		
			
			if(topicListToInsert != null && topicListToInsert.size() > 0){
				insert topicListToInsert; 
			}
				        	
        }
        
        
    }
    
    public void finish(Database.BatchableContext BC){
    }

}

 

Writing test class for a batch apex is quite simple.

  1. Set up the data in test class for the batch apex to process.
  2. Execute the batch apex.
  3. Check whether the batch processed the data correctly.

Make sure the executeBatch method is surrounded by test methods startTest and stopTest test to ensure the batch executes fully before test your assert statements.

/**
 * Test class for BatchNewTopicsUpdate
 */
@isTest()
public class BatchNewTopicsUpdateTest {

    static testMethod void myUnitTest() {
    	
    	Account account1 = new Account (name='test_Account1', Keywords__c ='topic1 , topic2 ');
    	Insert account1;
    	
    	Account account2 = new Account (name='test_Account123', Keywords__c ='topic1 , topic3 ');
    	Insert account2;

        Test.StartTest();

        BatchNewTopicsUpdate newTopicsUpdate = new BatchNewTopicsUpdate();
     	
     	Database.executeBatch(newTopicsUpdate);
	    
	    Test.StopTest();   
        System.AssertEquals(database.countquery('SELECT COUNT()'+' FROM Topic '), 3);
    }
}

 

Note:

When testing your batch Apex, you can test only one execution of the execute method. Use the scope parameter of the executeBatch method to limit the number of records passed into the execute method to ensure that you aren’t running into governor limits.

Use the System.Test.enqueueBatchJobs and System.Test.getFlexQueueOrder methods to enqueue and reorder no-operation jobs within the contexts of tests.

Hope this example helps.

Reference links:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm

Cheers !!! yes

Happy coding... heart

Rating: 
No votes yet