Test class for Batch Apex class that sends out emails in Salesforce
@isTest
public class EmailBatchClassTest {
@isTest
static void testEmailBatch() {
// Step 1: Setup Test Data
List<Contact> contacts = new List<Contact>();
contacts.add(new Contact(LastName = 'Doe', Email = 'test@example.com'));
insert contacts;
// Create email message list to pass to batch
List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();
for (Contact contact : contacts) {
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] { contact.Email });
email.setSubject('Test Email');
email.setPlainTextBody('Hello, this is a test email.');
emailMessages.add(email);
}
// Step 2: Execute the Batch Job
Test.startTest();
EmailBatchClass emailBatch = new EmailBatchClass(emailMessages);
Database.executeBatch(emailBatch, 1); // Batch size of 1 for simplicity
Test.stopTest();
// Step 3: Verify that emails were sent
List<Messaging.SendEmailResult> results = [SELECT StatusCode, Success FROM AsyncApexJob WHERE JobType='BatchApex'];
// Make assertions
System.assertEquals(emailMessages.size(), results.size(), 'Expected number of emails to be sent.');
for (Messaging.SendEmailResult result : results) {
System.assert(result.isSuccess(), 'Expected email to be sent successfully.');
}
}
}
Test class for Batch Apex class that sends out emails in Salesforce
Reviewed by dasfrogpractice
on
02:48
Rating:
No comments: