如何测试Java中调用System.exit()的场景?
在某种场景下,我想测试应用程序进行函数调用来发送电子邮件,然后调用 System.exit(0)
这是一个 Java 应用程序,而 Mockito 是被用来嘲笑。
我的测试目前看起来像这样:
testSendsEmailInScenario() {
// set up
foo.bar(mock);
ArgumentCaptor<HashMap> argument = ArgumentCaptor.forClass(HashMap.class);
verify(mockEmailDeliveryManager).send(argument.capture());
Map<String,String> argMap = argument.getValue();
// Test that map contains the right stuff
}
所以这不起作用,因为在应用程序中调用 send
之后,调用 System.exit()
,这会终止测试没有测试成功或失败。
由于 exit()
是 System
的静态方法,因此我无法使用 Mockito 来模拟它。那么我该如何:
- 为了这个测试而暂停现有的行为。
- 编写第二个测试来确认退出发生。 (只有调用
System.exit()
时测试才会成功,否则会失败。)
Possible Duplicate:
Java: How to test methods that call System.exit()?
In a certain scenario, I want to test that the application makes a function call to send an email, and then calls System.exit(0)
This is a Java application, and Mockito is being used for mocking.
My test currently looks something like this:
testSendsEmailInScenario() {
// set up
foo.bar(mock);
ArgumentCaptor<HashMap> argument = ArgumentCaptor.forClass(HashMap.class);
verify(mockEmailDeliveryManager).send(argument.capture());
Map<String,String> argMap = argument.getValue();
// Test that map contains the right stuff
}
So this doesn't work, because after the call to send
in the application, System.exit()
is called, which terminates the test without the test either succeeding or failing.
Since exit()
is a static method of System
, I can't mock it with Mockito. So how do I:
- Suspend the exiting behavior for the sake of this test.
- Write a second test that will confirm that the exit happened. (A test that succeeds only if
System.exit()
is called, and fails otherwise.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我使用以下非常简单的场景:我使用 Groovy - MockFor 可以保证调用某个方法。我尝试过,它甚至可以与系统类一起使用。
I use following very simple scenario: I use Groovy - MockFor which can guarantee for you that some method is called. I tried, it is working with even System classes.