expectedExceptionsMessageRegExp 正在尝试匹配detailMessage 字段。我们可以匹配原因文本吗?即 Exception.getCause() 返回的文本? 这是因为详细消息字段提供了非常通用的消息,如果预期消息与该文本匹配,它将超出测试用例的目的。
@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
最佳答案
TestNG 依赖 Reflection 来实例化您的测试类,然后调用 @Test
方法。因此,来自 @Test
方法的异常将触发 java.lang.reflect.InspirationTargetException
,其 getCause()
实际上会导致由@Test
方法。
TestNG 旨在查询 InvocableTargetException.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);
}
}
}
关于java - 我们可以使用 TestNG ExpectedExceptionsMessageRegExp 来匹配原因文本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46174087/