【问题标题】:How to test for exception in DrJava?如何在 DrJava 中测试异常?
【发布时间】:2013-08-30 18:53:18
【问题描述】:

我开始使用 DrJava 学习 Java。我正在关注 TDD 进行学习。我创建了一个假设验证某些数据和无效数据的方法,该方法假设抛出异常。

它按预期抛出异常。但我不确定,如何编写单元测试来期待异常。

在 .net 中,我们有 ExpectedException(typeof(exception))。有人可以指出 DrJava 中的等价物吗?

谢谢

【问题讨论】:

  • 你需要使用 DrJava 吗?

标签: java drjava


【解决方案1】:

如果你使用的是 JUnit,你可以这样做

@Test(expected = ExpectedException.class)
public void testMethod() {
   ...
}

查看API了解更多详情。

【讨论】:

  • 在旧版本的 JUnit 中,您可以执行类似 try { doSomething(); fail("expected an exception"); } catch (ExpectedException e) {} 的操作
  • OP 是从 Java 开始的,所以他不妨学习最先进的实践,因为无论如何它们很快就会过时。
【解决方案2】:

如果您只是想测试在您的测试方法中某处引发了特定异常类型的事实,那么已经显示的@Test(expected = MyExpectedException.class) 就可以了。

要对异常进行更高级的测试,您可以使用@Rule,以便进一步细化您期望抛出异常的位置,或者添加关于抛出的异常对象(即消息字符串)的进一步测试等于某个期望值或包含某个期望值:

class MyTest {

   @Rule ExpectedException expected = ExpectedException.none();
   // above says that for the majority of tests, you *don't* expect an exception

   @Test
   public testSomeMethod() {
   myInstance.doSomePreparationStuff();
   ...
   // all exceptions thrown up to this point will cause the test to fail

   expected.expect(MyExpectedClass.class);
   // above changes the expectation from default of no-exception to the provided exception

   expected.expectMessage("some expected value as substring of the exception's message");
   // furthermore, the message must contain the provided text

   myInstance.doMethodThatThrowsException();
   // if test exits without meeting the above expectations, then the test will fail with the appropriate message
   }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 2018-07-20
    • 2017-06-18
    相关资源
    最近更新 更多