Reputation: 1019
I want my unit test classes to check for the error code (which is a custom property of my exception class) and assert when an exception is thrown from the tested code. Can I do this using testng.
I have the following exception class :
public final class CustomException extends Exception {
public CustomException(String msg,String errorCode,Throwable cause) {
super(msg,cause);
this.errorCode = errorCode;
}
private String errorCode;
public String getErrorCode() {
return this.errorCode;
}
}
My Unit Test Class :
import org.testng.annotations.Test;
public class MyUnitTestClass {
@Test(priority = 25,
expectedExceptions = CustomException.class,
expectedExceptionsMessageRegExp = "Error while doing something.")
public void testDoSomething() {
// code to invoke doSomething();
// which throws CustomException on some exception.
}
}
Instead of expectedExceptionsMessageRegExp="Error while doing something."
i want to assert on an error code Eg: like "ERR100909" which will be set in the errorCode property of CustomException class.
Unit Test Framework : Testng Version : 6.9.4
Thanks!
Upvotes: 1
Views: 788
Reputation: 14746
One of the ways in which you can do this is by implementing IHookable
interface. Here's a sample that shows this in action.
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
public class MyUnitTestClass implements IHookable {
private List<String> errorCodes = Arrays.asList("ERR100909", "ERR100");
@Override
public void run(IHookCallBack callBack, ITestResult testResult) {
callBack.runTestMethod(testResult);
Throwable t = testResult.getThrowable();
if (t != null) {
t = t.getCause();
}
boolean shouldFail = (t instanceof CustomException && errorCodes.contains(((CustomException) t).getErrorCode()));
if (!shouldFail) {
testResult.setThrowable(null);
testResult.setStatus(ITestResult.SUCCESS);
}
}
@Test
public void test1() throws CustomException {
throw new CustomException("test", "ERR100", new Throwable());
}
@Test
public void test2() throws CustomException {
throw new CustomException("test", "ERR500", new Throwable());
}
}
Upvotes: 2