如果我只想测试类型和消息,我可以使用这个:
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void test(){
exception.expect(anyException.class);
exception.expectMessage("Expected Message");
//your code expecting to throw an exception
}
但是如果我想测试其他属性,我没有找到与下面不同的方法:
try{
//your code expecting to throw an exception
fail("Failed to assert :No exception thrown");
} catch(anyException ex){
assertNotNull("Failed to assert", ex.getMessage())
assertEquals("Failed to assert", "Expected Message", ex.getMessage());
assertEquals("Failed to assert getter", expectedGetterValue , ex.getAnyCustomGetter());
}
有没有更好的办法?
最佳答案
ExpectedException.expect(Matcher<?> matcher);
例如...
public class MyExceptionMatcher extends BaseMatcher<AnyException> {
public static MyExceptionMatcher matchesSomeCriteria(...) {
return new MyExceptionMatcher (...);
}
public MyExceptionMatcher(...) {
....
}
public boolean matches(Object item) {
...implement your matching logic here
}
}
这样你就可以...
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void test(){
exception.expect(anyException.class);
exception.expectMessage("Expected Message");
expection.expect(matchesSomeCriteria(...)); // static import
}
关于java - 在 Java 中如何验证 JUnit 4 异常中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39377292/