java - 在 Java 中如何验证 JUnit 4 异常中的值?

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

有没有更好的办法?

最佳答案

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/

相关文章:

java - 我的 ScheduledThreadPoolExecutor 没有关闭

java - 小服务程序 : Opening of a new window with http 404 error with IE6 when download a file (but file dowloaded)

.net - 使用 dotCover 时测试结果不一致

java - 在 JUnit 故障跟踪中显示错误

unit-testing - 是否可以通过电子邮件发送 JUnit 测试报告?

java - 在android中保持常量的最佳方法

Java - Rome rss 阅读器?

node.js - 错误 : Cannot find module 'tap'

asp.net-mvc - 如何在 MSTest 中对 JsonResult 和集合进行单元测试

spring - 如何使用 MockMvc 测试 spring Controller 方法?