如何在 JUnit 3 中自定义异常处理行为?
我想使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决方案是否
适合您的想法?
另请查看此线程,其中有人为 JUnit3 创建了代理解决方案这似乎是解决你的问题的另一种可能性。
Would the solution:
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.
无需实现您自己的解决方案,因为已经有一个可以与 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.
最简单的方法是使用 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 aTest
. I forget the details, but we can override the execution of the test (which the framework initially calls throughrun(TestResult)
specified inTest
). In that override we can place the try-catch, as per Execute Around. ThetestXxx
method should call a set method to install the expected exception type.