How to test for exceptions in unit tests?
May 22, 2021
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);
}