如何在 Java 中使用 Hamcrest 来测试异常?

新手上路,请多包涵

我如何使用 Hamcrest 来测试异常?根据 https://code.google.com/p/hamcrest/wiki/Tutorial 中的评论,“异常处理由 Junit 4 使用预期属性提供。”

所以我尝试了这个并发现它有效:

 public class MyObjectifyUtilTest {

    @Test
    public void shouldFindFieldByName() throws MyObjectifyNoSuchFieldException {
        String fieldName = "status";
        String field = MyObjectifyUtil.getField(DownloadTask.class, fieldName);
        assertThat(field, equalTo(fieldName));
    }

    @Test(expected=MyObjectifyNoSuchFieldException.class)
    public void shouldThrowExceptionBecauseFieldDoesNotExist() throws MyObjectifyNoSuchFieldException {
        String fieldName = "someMissingField";
        String field = MyObjectifyUtil.getField(DownloadTask.class, fieldName);
        assertThat(field, equalTo(fieldName));
    }

}

Hamcrest 是否提供了 JUnit 的 @Test(expected=...) 注释之外的任何附加功能?

虽然有人在 Groovy 中询问了这个问题( 如何使用 Hamcrest 来测试异常? ),但我的问题是针对用 Java 编写的单元测试。

原文由 Michael Osofsky 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 452
1 个回答

您真的需要使用 Hamcrest 库吗?

如果没有,这里是你如何使用 Junit 对异常测试的支持。 ExpectedException 类有很多方法可以用来做你想做的事,除了检查抛出的类型 Exception

您可以结合使用 Hamcrest 匹配器来声明特定的内容,但最好让 Junit 期待抛出的异常。

 public class MyObjectifyUtilTest {

    // create a rule for an exception grabber that you can use across
    // the methods in this test class
    @Rule
    public ExpectedException exceptionGrabber = ExpectedException.none();

    @Test
    public void shouldThrowExceptionBecauseFieldDoesNotExist() throws MyObjectifyNoSuchFieldException {
        String fieldName = "someMissingField";

        // a method capable of throwing MyObjectifyNoSuchFieldException too
        doSomething();

        // assuming the MyObjectifyUtil.getField would throw the exception,
        // I'm expecting an exception to be thrown just before that method call
        exceptionGrabber.expect(MyObjectifyNoSuchFieldException.class);
        MyObjectifyUtil.getField(DownloadTask.class, fieldName);

        ...
    }

}

这种方法比

  • @Test (expected=...) 方法因为 @Test (expected=...) 只测试方法执行是否通过抛出给定的异常而停止,而不是如果 你想抛出异常的调用 抛出一个。例如,测试将成功,即使 doSomething 方法抛出 MyObjectifyNoSuchFieldException 异常,这可能是不可取的

  • 您要测试的不仅仅是抛出的异常类型。例如,您可以检查特定的异常实例或异常消息等

  • try/catch 块方法,因为可读性和简洁性。

原文由 mystarrocks 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题