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
Kelly KKelly K 

Code Coverage for Batch finish() Email Distribution List

Hi All,

I have a batch class that sends an email in the finish() method whenver errors are present. The email distribution list is set up under custom settings so it can be easily adjusted without having to directly modify the code in a sandbox, turn off the batch schedule, push the new code in, and turn the schedule back on.

I'm being a bit anal about this, but I would like to see 100% code coverage for my batch class - but I'm not sure how to write it up in my test class approrpriately. 

Here's the finish method:
global void finish(Database.BatchableContext BC) {
		AsyncApexJob job = [SELECT Id, ApexClassId, JobItemsProcessed, TotalJobItems, NumberOfErrors, CreatedBy.Email
							FROM AsyncApexJob WHERE Id = :BC.getJobId()];

		if(failedUpdates > 0 || job.NumberOfErrors > 0) {
			String emailMessage = 'Batch Job TaskUpdateActivityInfo has errors. <br/><br/>'
								 +'Number of batches: ' + job.TotalJobItems + '<br/>'
								 +'Number of successful batches: ' + job.JobItemsProcessed + '<br/>'
								 +'Number of unsuccessful batches: ' + job.NumberOfErrors + '<br/>'
								 +'Number of unsucessful record updates: ' + failedUpdates + '<br/><br/>'
								 +'For more details, please review the Apex Errors tab.';

			Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

			//Uses custom setting to add other email addresses
			String[] toAddresses = new String[] {job.CreatedBy.email};

			Map<String, Apex_Distribution_List__c> distList = Apex_Distribution_List__c.getAll();
	        String serverhost = URL.getSalesforceBaseUrl().getHost().left(2);

	        for(Apex_Distribution_List__c record : distList.values()) {
	            //If it's a produciton environment, add only system admin emails
	            if(serverHost == 'na')
	            	if(record.System_Admin_Email__c)
	            		toAddresses.add(record.Email__c);
	            //Otherwise, only add those that are enabled for sandbox alerts
	            else
	                if(record.Enabled_for_Sandbox_Alerts__c)
	                	toAddresses.add(record.Email__c);
	        }

			mail.setToAddresses(toAddresses);
			mail.setReplyTo('kkorynta@navicure.com');
			mail.setSenderDisplayName('Salesforce Apex Batch Job Summary');
			mail.setSubject('Salesforce Batch Job Summary: Task Update Activity Info');
			mail.setHTMLBody(emailMessage);
			Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
		}
	}

These are the lines I'm not able to get coverage on:
//If it's a produciton environment, add only system admin emails
	            if(serverHost == 'na')
	            	if(record.System_Admin_Email__c)
	            		toAddresses.add(record.Email__c);
	            //Otherwise, only add those that are enabled for sandbox alerts
	            else
	                if(record.Enabled_for_Sandbox_Alerts__c)
	                	toAddresses.add(record.Email__c);


Does anyone have any suggestions on how to get coverage on this? I'm at 91% currently.

Thanks,
Kelly
Best Answer chosen by Kelly K
anto nirmalanto nirmal

Hi Kelly,

Appreciate your spirit in getting 100% code coverage.
You could try the below code to attain 100%.
//If it's a produciton environment, add only system admin emails 
if((serverHost == 'na') OR Test.isRunningTest()) 
  if(record.System_Admin_Email__c) 
    toAddresses.add(record.Email__c); 
//Otherwise, only add those that are enabled for sandbox alerts 
if((serverHost != 'na') OR Test.isRunningTest()) 
  if(record.Enabled_for_Sandbox_Alerts__c) 
    toAddresses.add(record.Email__c);

Let me know if this helps.

As a common practice, if your question is answered, please choose 1 best answer.
Additionally you can give every answer a like if that answer is helpful to you.

Regards,
Anto Nirmal

All Answers

anto nirmalanto nirmal

Hi Kelly,

Appreciate your spirit in getting 100% code coverage.
You could try the below code to attain 100%.
//If it's a produciton environment, add only system admin emails 
if((serverHost == 'na') OR Test.isRunningTest()) 
  if(record.System_Admin_Email__c) 
    toAddresses.add(record.Email__c); 
//Otherwise, only add those that are enabled for sandbox alerts 
if((serverHost != 'na') OR Test.isRunningTest()) 
  if(record.Enabled_for_Sandbox_Alerts__c) 
    toAddresses.add(record.Email__c);

Let me know if this helps.

As a common practice, if your question is answered, please choose 1 best answer.
Additionally you can give every answer a like if that answer is helpful to you.

Regards,
Anto Nirmal
This was selected as the best answer
Kelly KKelly K

Fabulous. Now I'm at 100%. Thank you.

//If it's a produciton environment, add only system admin emails
                if(serverHost == 'na' || Test.isRunningTest())
                    if(record.System_Admin_Email__c)
                        toAddresses.add(record.Email__c);
                //Otherwise, only add those that are enabled for sandbox alerts
                if(serverHost != 'na' || Test.isRunningTest())
                    if(record.Enabled_for_Sandbox_Alerts__c)
                        toAddresses.add(record.Email__c);