Testng:使用错误代码断言,自定义异常实例的自定义属性

时间:2017-12-12 12:50:42

标签: java unit-testing testng

我希望我的单元测试类检查错误代码(这是我的异常类的自定义属性),并在测试代码抛出异常时断言。我可以使用testng做到这一点。

我有以下异常类:

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;
    }
}

我的单元测试类:

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.
    }
}

而不是expectedExceptionsMessageRegExp="Error while doing something."我想在错误代码上断言例如:像“ERR100909”,它将在CustomException类的errorCode属性中设置。

单元测试框架:Testng 版本:6.9.4

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以通过实施IHookable界面的方式之一。这是一个显示实际情况的示例。

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());
    }
}