This article describes how to assert exceptions in Apex test classes.
Below is an example of the class to be tested:
public class SampleClass {
public static boolean isGreaterThanTen(String val){
if(String.isBlank(val) || !val.isNumeric()){
throw new IllegalArgumentException('Illegal');
}
return Integer.valueOf(val) > 10;
}
}
In this sample, the method returns true
if the given string is numeric and greater than 10, and throws an IllegalArgumentException if the input is not numeric.
To test exception handling, write the test class as follows:
@IsTest
private class SampleClassTest {
@IsTest
static void alphabetTest(){
Test.startTest();
try {
boolean ret = SampleClass.isGreaterThanTen('a');
Assert.fail();
} catch (IllegalArgumentException e) {
System.assertEquals('Illegal' , e.getMessage());
}
Test.stopTest();
}
}
There are two key points:
- Call the method under test within a try block and assert in the
catch
block. - Place Assert.fail() immediately after the method call under test.
The second point, placing Assert.fail(), is particularly important.
If the isGreaterThanTen method does not throw the expected exception, the test will pass without Assert.fail().
When asserting exceptions, always include Assert.fail() in the normal execution path.