在Java中,如何使用JUnit4验证异常中的值?
如果我只想测试类型和消息,我可以使用:在Java中,如何使用JUnit4验证异常中的值?,java,unit-testing,junit,Java,Unit Testing,Junit,如果我只想测试类型和消息,我可以使用: @Rule public ExpectedException exception = ExpectedException.none(); @Test public void test(){ exception.expect(anyException.class); exception.expectMessage("Expected Message"); //your code expecting to throw an e
@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());
}
有更好的方法吗?通常不赞成在生产代码中捕获异常,但由于这是一个单元测试,我在您的第二个代码段中没有发现这种方法有任何错误。所有变体都写了下来,如果我使用hamcrest hasProperty,在github wiki上有junit4的好例子,这难道不应该比创建我自己的matcher更好吗?hasProperty测试对象是否有一个具有给定名称的属性,而不是该对象的值。。。也许你的意思是有价值的财产?无论如何,是的,你也可以做到。就个人而言,我喜欢自定义匹配器,因为它们允许您更清楚地表达代码的功能,但这也是一个品味问题。
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
}