Let’s consider the Account object for this scenario. Imagine we create two custom fields on the Account object:
- Has_Services__c (Checkbox): This field serves to indicate whether an account has active services associated with it.
- Service_Renewal_Date__c (Date): This field is designed to store the renewal date of the services linked to the account.
Trigger
trigger AccountTrigger on Account (before insert, before update) {
if(Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate)) {
AccountTriggerHandler.handleServices(trigger.new);
}
}
Apex Class
public class AccountTriggerHandler {
public static void handleServices(List<account> newAccounts){
for (Account acc : newAccounts) {
// If Has_Services__c is true, ensure Service_Renewal_Date__c is not null
if (acc.Has_Services__c && acc.Service_Renewal_Date__c == null) {
acc.addError('Please enter the Service Renewal Date for accounts with active services.');
}
}
}
}
Apex Test Class
@isTest
private class AccountTriggerHandlerTest {
// Test method to cover scenario where Has_Services__c is true and Service_Renewal_Date__c is null
@isTest
static void testAccountWithServicesAndNullRenewalDate() {
// Create a new Account with Has_Services__c true and Service_Renewal_Date__c as null
Account acc = new Account(
Name = 'Test Account',
Has_Services__c = true
// Service_Renewal_Date__c is intentionally left null
);
System.Test.startTest();
try {
insert acc;
// If the validation is properly set up, this should throw an error
System.assert(false, 'Expected validation rule to prevent saving with null Service_Renewal_Date__c');
} catch (DmlException e) {
// Ensure the correct error message is returned
System.assertEquals('Please specify the Service Renewal Date.', e.getDmlMessage(0));
}
System.Test.stopTest();
}
// Test method to cover scenario where Has_Services__c is false and Service_Renewal_Date__c is null
@isTest
static void testAccountWithoutServicesAndNullRenewalDate() {
// Create a new Account with Has_Services__c false and Service_Renewal_Date__c as null
Account acc = new Account(
Name = 'Test Account',
Has_Services__c = false
// Service_Renewal_Date__c is intentionally left null
);
System.Test.startTest();
try {
insert acc;
// If the validation is properly set up, this should not throw an error
System.assert(true);
} catch (DmlException e) {
// If an error occurs unexpectedly, fail the test
System.assert(false, 'Unexpected error: ' + e.getDmlMessage(0));
}
System.Test.stopTest();
}
}