How to test for exceptions in unit tests?

--

If your code is expected to throw an exception, how do you write a unit test to cover such a scenario?

…Simply wrap the call to the method in a try/catch block as follows

@isTest

private static void myUnitTest_VerifiesExceptionIsThrown() {

String errorMessage;

try {

MethodCallExpectedToThrowException();

} catch (Exception e) {

errorMessage = e.getMessage();

}

System.assertNotEquals(null, errorMessage);

}

--

--

Manisha Nundloll-Rice
Manisha Nundloll-Rice

Written by Manisha Nundloll-Rice

Salesforce Developer/Lead with over 10 years of Salesforce Experience. Experience in Apex, VisualForce, Lightning Web Components.

No responses yet