如何在 JUnit 3 中自定义异常处理行为?

发布于 2024-07-14 23:54:26 字数 342 浏览 4 评论 0原文

我想使用 JUnit 3 实现异常检查(如 JUnit 4 中的情况)。例如,我希望能够编写如下测试:

public void testMyExceptionThrown() throws Exception {
    shouldThrow(MyException.class);

    doSomethingThatMightThrowMyException();
}

当且仅当引发 MyException 时,此操作才会成功。 JUnit 中有 ExceptionTestCase 类,但我想要每个 test* 方法都可以决定使用或不使用的东西。 实现这一目标的最佳方法是什么?

I want to implement exception checking (like in JUnit 4) using JUnit 3. For example, I would like to be able to write tests like this:

public void testMyExceptionThrown() throws Exception {
    shouldThrow(MyException.class);

    doSomethingThatMightThrowMyException();
}

This should succeed if and only if a MyException is thrown.
There is the ExceptionTestCase class in JUnit, but but I want something that each test* method can decide to use or not use. What is the best way to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

若水般的淡然安静女子 2024-07-21 23:54:26

解决方案是否

public void testMyExceptionThrown() throws Exception {
    try {
      doSomethingThatMightThrowMyException();
      fail("Expected Exception MyException");
    } catch(MyException e) {
      // do nothing, it's OK
    }
}

适合您的想法?

另请查看此线程,其中有人为 JUnit3 创建了代理解决方案这似乎是解决你的问题的另一种可能性。

Would the solution:

public void testMyExceptionThrown() throws Exception {
    try {
      doSomethingThatMightThrowMyException();
      fail("Expected Exception MyException");
    } catch(MyException e) {
      // do nothing, it's OK
    }
}

be suitable for what you're thinking of?

Also have a look at this thread, where someone created a Proxy-solution for JUnit3 which seems to be another possibility to solve your problem.

我还不会笑 2024-07-21 23:54:26

无需实现您自己的解决方案,因为已经有一个可以与 JUnit3(以及任何其他测试框架)一起使用的解决方案:捕获异常

There is no need to implement your own solution because there is already one that can be used with JUnit3 (and any other testing framework): catch-exception.

风筝有风,海豚有海 2024-07-21 23:54:26

最简单的方法是使用 Execute around 习惯用法来抽象出您通常编写的 try-catch。

更复杂的是要注意 TestCase 只是一个 Test。 我忘记了细节,但我们可以重写测试的执行(框架最初通过 Test 中指定的 run(TestResult) 调用)。 在该覆盖中,我们可以按照 Execute around 放置 try-catch。 testXxx 方法应调用 set 方法来安装预期的异常类型。

The simplest approach is to use the Execute Around idiom to abstract away the try-catch that you would usually write.

More sophisticated is to note that TestCase is just a Test. I forget the details, but we can override the execution of the test (which the framework initially calls through run(TestResult) specified in Test). In that override we can place the try-catch, as per Execute Around. The testXxx method should call a set method to install the expected exception type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文