【问题标题】:Can we use TestNG expectedExceptionsMessageRegExp to match the cause text?我们可以使用 TestNG expectedExceptionsMessageRegExp 来匹配原因文本吗?
【发布时间】:2017-09-12 10:31:02
【问题描述】:

expectedExceptionsMessageRegExp 正在尝试匹配 detailMessage 字段。我们可以匹配原因文本吗?即 Exception.getCause() 返回的文本? 这是因为 detailMessage 字段提供了非常通用的消息,如果预期消息与该文本匹配,它将超出测试用例的目的。

@Test(expectedExceptions = TestExecutionException.class, expectedExceptionsMessageRegExp = ".* HTTP 422.*")
public void test() throws Exception {
    ..
    //some code that produces TestExecutionException with the cause HTTP 422
    ..
}

TestNG 错误是:

The exception was thrown with the wrong message: expected ".* HTTP 422.*" but got "Failed executing MessageExecutionTask"
    at org.testng.internal.Invoker.handleInvocationResults(Invoker.java:1481)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:754)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    ... 16 more

【问题讨论】:

    标签: java testng http-error


    【解决方案1】:

    TestNG 依赖反射来实例化您的测试类,然后调用@Test 方法。因此,@Test 方法的异常将触发 java.lang.reflect.InvocationTargetException,其 getCause() 实际上会导致 @Test 方法引发的异常。

    TestNG 旨在查询InvocationTargetException.getCause().getMessage() 以获取引发的异常的错误消息,然后尝试使用通过@Test 注释的expectedExceptionsMessageRegExp 属性提供的正则表达式匹配它。

    这是一个使用 TestNG 6.12 运行良好的示例

    import org.testng.ITestResult;
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.Test;
    
    public class TestClass {
    
        @Test(expectedExceptions = OldMonkException.class, expectedExceptionsMessageRegExp = ".* HTTP 422.*")
        public void test() throws Exception {
            throw new OldMonkException("Your have triggered a HTTP 422 error code.");
        }
    
        @AfterMethod
        public void afterTestMethod(ITestResult testResult) {
            String mname = testResult.getMethod().getMethodName() + " ";
            switch (testResult.getStatus()) {
                case ITestResult.SUCCESS:
                    mname += "passed";
                    break;
                case ITestResult.FAILURE:
                    mname += "failed";
                    break;
                case ITestResult.SKIP:
                    mname += "skipped";
                    break;
                default:
                    mname += "";
            }
            System.err.println(mname);
        }
    
        public static class OldMonkException extends Exception {
            OldMonkException(String message) {
                super(message);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多