【发布时间】:2019-01-05 20:16:59
【问题描述】:
我的应用程序有一个流程,最后调用了方法 System.exit(int)。
我正在尝试通过使用 TestNG 运行测试来测试此流程。
但是,在运行测试时,尽管测试已完成,但我收到了这条奇怪的消息:
为了找到根本原因,我把System.exit(int)从实际流程中去掉了,测试按预期通过了,所以这里的问题是System.exit(int)方法。
为了解决这个问题,我尝试模拟有问题的方法,但找不到正确的方法。这就是我所做的
- 我在测试类的
@PrepareForTest下添加了java.lang.System.class。 - 在测试中添加了
PowerMockito.mockStatic(java.lang.System.class) -
我尝试以两种方式模拟该方法:
一个。
PowerMockito.replace(PowerMockito.method(System.class, "exit", int.class)) .with((proxy, method, args) -> null);当以这种方式运行时,mock 似乎不起作用,因为我在测试结束时收到了相同的消息,在 System.exit(int) 上没有应用任何 mocks 时我也收到了相同的消息
b.
PowerMockito.doNothing().when(System.class, "exit", Mockito.any());
通过这种方式,我在测试开始时遇到了这个异常:
org.powermock.reflect.exceptions.MethodNotFoundException: No method found with name 'exit' with parameter types: [ <none> ] in class java.lang.System.
我已经以这种方式模拟了一些方法,不知道为什么 System.exit(int) 不起作用。
有什么想法吗? 谢谢
【问题讨论】:
-
我认为这根本不是一个好主意。你应该认真考虑重新设计你的系统,只在你的 main 方法中调用
System.exit,而不是其他地方。 -
我无法更改此代码,我必须找到模拟问题的解决方案
-
经过检查,System.exit() 只在应用程序末尾的一个地方使用!不知道为什么它在调用 System.exit() 后将测试显示为“未开始”(如上图所示)。删除 System.exit() 时,测试成功通过。
-
所以你的问题已经解决了,不是吗?
-
一点也不。我已经编辑了这个问题。希望现在更清楚了。
标签: java testng powermock powermockito