在Java中,如何使用JUnit 4验证异常中的值?

时间:2016-09-07 18:57:26

标签: 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 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());
}

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

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
}