Created
December 5, 2023 05:32
-
-
Save burlistic/50d038940408f19a18c05cb03661faea to your computer and use it in GitHub Desktop.
APEX SalesForce Contact Trigger with Tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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