5

My Requirement is I have to cover so.AddError() in the test class.

Apex Class:

if(accountToUpdate.Inactive__c== true && accountToUpdate.Inactive__c <> accountBeforeUpdate.Inactive__c)
        {
           List <Contact> cnt= new List <Contact>([Select Id,Name,Inactive__c FROM Contact WHERE AccountId =:accountToUpdate.Id AND Inactive__c=false]);

       if(cnt.size()>0)
            {
                so.addError(Label.Active_Error);
            }
        }

Test Class {

Account acct = TestData.createAccount('TestInactive','Customer' ,true);


     Account ac=[Select id from account where id=:acct.Id];
     system.Assert(ac!=null,'AccountHandlerTest.testInactive FAIL:Account was not inserted properly!');

 Contact cnt=TestData.createContact('Test','Contact','[email protected]',ac.Id,true);

           Contact cn=[Select Id from Contact where AccountId=:ac.Id];
            system.Assert(ac!=null,'AccountHandlerTest.testInactive FAIL:Account was not inserted properly!');
        Test.startTest();
        try{
        cn.inactive__c=false;
        update cn;
        ac.inactive__c = true;
        update ac;

        system.assert(true,'You can not inactivate this account ');
        }
        catch(Exception e)
        {
        String message = e.getMessage();
         system.assert(message.contains('Active_Contact_Error'), 'message=' + message);

        }

       Test.StopTest();
}

Can someone tell me what I miss in test class? so.addError(Label.Active_Error) is not covering in code coverage.

If I add Custom message instead of Label then it completes the code coverage.How can I cover label message here.

2 Answers 2

6

Do this in catch block :

Boolean expectedExceptionThrown =  ex.getMessage().contains('Script-thrown exception') ? true : false;
System.assertEquals(expectedExceptionThrown, false);
OR
System.assertEquals(expectedExceptionThrown, true);

Depending on what you are expecting!

3
  • Superb!! Thank You....I have also added system.assert(expectedExceptionThrown,ex.getMessage)..the code coverage is successfully done....
    – SFDCDJ
    Jun 24, 2016 at 13:57
  • Glad I could help!
    – d_k
    Jun 24, 2016 at 14:00
  • 3
    Except if you never hit the catch block you don't assert anything...
    – Adrian Larson
    Jun 24, 2016 at 20:40
8

A more complete example based on d_k answer, but handles the exception not being thrown, as pointed out by Adrian Larson.

@isTest
public static void testMethod() {

    // arrange
    Boolean exceptionThrown = false;

    try {

        // act 

    } catch (Exception e) {
        exceptionThrown = true;

        // assert
        Boolean expectedExceptionThrown =  (e.getMessage().contains('error msg')) ? true : false; 
        System.AssertEquals(true, expectedExceptionThrown, e.getMessage()); 
    } 

    System.assertEquals(true, exceptionThrown, 'No exception was thrown');
}

An alternative approach would be to do this:

@isTest
public static void testMethod() {

    // arrange
    Account record = new Account();

    // act 
    Test.startTest();
    Database.SaveResult result = Database.insert(record, false);
    Test.stopTest();

    // assert
    System.assert(result.isSuccess() == false);
    System.assert(result.getErrors().size() == 1);
}
1
  • 1
    Although I prefer the second method, if I had to use the first method, I prefer to use try { <statementToTest>; System.assert(false, 'should not have reached here'); } catch(){..} rather than a boolean variable :)
    – markgarg
    Apr 9, 2021 at 10:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .