Home SALESFORCEAPEX How to write apex test class to cover the apex trigger addError() message

How to write apex test class to cover the apex trigger addError() message

This post to describes to cover the addError() message from Apex Triggers, if we added any custom logics to validate and through the error message from apex trigger, then its require to write the test class to cover the addError part and below are the sample example:

Example Apex Trigger to display error message when adding the account name as “THEBLOGREADERS.COM

trigger AccountTrigger on Account(before insert, before update) {
    
    for (Account acc : Trigger.New) {
        if(acc.Name == 'THEBLOGREADERS.COM') {   
            acc.AddError('THEBLOGREADERS.COM is not allowed for Account Creations');
        }
    }
}

Example 1: Test Class to Cover addError:

@isTest
private class TestRestrictAccountName {
    @isTest static void test() {
        Account acc = new Account(Name = 'THEBLOGREADERS.COM');
        Database.SaveResult result = Database.insert(acc, false);
        System.assertEquals('THEBLOGREADERS.COM is not allowed for Account Creations',result.getErrors()[0].getMessage());
    }
}

Example 2: Test Class to Cover addError:

@isTest
private class TestRestrictAccountName {
    private static testmethod void runTest() {
        Account acc = new Account(Name = 'THEBLOGREADERS.COM');
        // Testing addError method of Trigger
        try {
            insert acc;
        }
        catch(Exception e) {
            System.assert(e.getMessage().contains('THEBLOGREADERS.COM is not allowed for Account Creations'));
        }
    }
}

also use the try catch to read the error message likely,

System.assert(e.getMessage().contains(‘THEBLOGREADERS.COM is not allowed for Account Creations’));

 

 

You may also like

Leave a Comment