Skip to content

Instantly share code, notes, and snippets.

@burlistic
Created December 5, 2023 05:32
Show Gist options
  • Save burlistic/50d038940408f19a18c05cb03661faea to your computer and use it in GitHub Desktop.
Save burlistic/50d038940408f19a18c05cb03661faea to your computer and use it in GitHub Desktop.
APEX SalesForce Contact Trigger with Tests
trigger RestrictContactByName on Contact (before insert, before update) {
//check contacts prior to insert or update for invalid data
For (Contact c : Trigger.New) {
if(c.LastName == 'INVALIDNAME') { //invalidname is invalid
c.AddError('The Last Name "'+c.LastName+'" is not allowed for DML');
}
}
}
@isTest
public class TestRestrictContactByName {
@isTest static void TestDeleteUpdateContactWithValidLastname() {
// Test data setup
// Create an account with an opportunity, and then try to delete it
Contact contact = new Contact(LastName='Test Contact');
insert contact;
// Perform test
Test.startTest();
Database.DeleteResult result = Database.delete(contact, false);
Test.stopTest();
// Verify
System.assert(result.isSuccess());
}
@isTest static void TestUpdateContactWithInvalidLastname() {
// Create an conact with an invalid last name
try{
Contact contact = new Contact(LastName='INVALIDNAME');
insert contact;
} catch(DmlException e) {
System.assertEquals('Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, The Last Name "INVALIDNAME" is not allowed for DML: []',
e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment