How to cover addError() in trigger in Apex Test?

Sample Trigger:

trigger RestrictContactByName on Contact (before insert, before update) {
    
    for (Contact c : Trigger.New) {
        if(c.LastName == 'INVALIDNAME') {   //invalidname is invalid
            c.AddError('The Last Name "'+c.LastName+'" is not allowed for DML');
        }

    }
}

Sample Test Class:

@isTest
private class TestRestrictContactByName {
    @isTest static void test() {
        Contact c = new Contact(LastName = 'INVALIDNAME');
        Database.SaveResult result = Database.insert(c, false);
        System.assertEquals('The Last Name "'+c.LastName+'" is not allowed for DML',result.getErrors()[0].getMessage());
    }
}

Cheers!!!

2 comments:

  1. Hi,
    you didn't mentioned class( nameRestrictContactByName ) in testclass,then how console knows that you have tested class(nameRestrictContactByName )

    ReplyDelete
    Replies
    1. RestrictContactByName is trigger. It's not a class.

      Delete