我想在 testng @test 中使用断言异常类型和消息,其中我的要求是从外部数据源传递预期消息,这看起来不容易用 @test 作为参数传递
尝试了这个测试解决方案
@Test(expectedExceptions = StatusRuntimeException.class , expectedExceptionsMessageRegExp ="ExceptionMsg")
想要实现类似给定的 Junit 示例的目标
@Test
public void testMethod(){
valiadteException();
}
public void valiadteException(){
exception.expect(StatusRuntimeException.class);
exception.expectMessage("ExceptionMsg");
}
最佳答案
您传递的正则表达式与输出消息不匹配。
如果您需要完整消息的一部分,请尝试使用:
@Test(expectedExceptions=StatusRuntimeException.class, expectedExceptionsMessageRegExp =".*ExceptionMsg.*")
这将检查消息中的某处是否包含ExceptionMsg
。
但是,如果 ExceptionMsg
是您期望的完整消息,则必须转义正则表达式特殊字符才能使其正常工作。
诸如 .
之类的特殊字符必须通过在特殊字符前面添加转义字符 \
进行转义,如下所示:\.
如果没有更具体的消息,我无法提供更多信息。如果您添加您期望的消息,我可以在我的答案中给出其转义版本。
编辑:
如果你想要像第二个这样的东西,我不知道它是否存在于 testng 中,但是你可以像这样完成它:
@Test
public void testMethod(){
// test code
try {
// call function/method that throws the StatusRuntimeException
} catch (StatusRuntimeException ex) {
// validate the exception
Assert.assertTrue(ex.getMessage().contains("ExceptionMsg"));
}
}
关于java - 如何在测试方法中使用expectedExceptionsMessageRegExp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56709599/