简体   繁体   English

如何使JUnit的行为与从命令行运行的Java相同

[英]How to make JUnit behave the same as the Java running from command line

I noticed that when a unit test exits, all the threads spawned are automatically killed, this is quite different from the java program running from command line. 我注意到当单元测试退出时,所有生成的线程都会被自动杀死,这与从命令行运行的java程序完全不同。 In the command line, the program does not exit until all the non deamon threads exit. 在命令行中,程序不会退出,直到所有非deamon线程退出。

How to test the case involving spawned thread using jUnit? 如何使用jUnit测试涉及衍生线程的案例?

If the method you are testing returns a reference to the thread it creates, then join on that. 如果您正在测试的方法返回对它创建的线程的引用,那么就加入它。 If it doesn't, create your own thread to call the method under test and join on that. 如果没有,请创建自己的线程来调用测试中的方法并加入其中。

I would suggest you make your unit test shutdown() its components such that it returns to the state before the test started. 我建议你让你的单元测试shutdown()它的组件,使它返回到测试开始前的状态。 This may not be actually required in the running system but it allows you to run multiple tests many times. 在运行的系统中可能实际上不需要这样做,但它允许您多次运行多个测试。

You may even like to take a snapshot of the running threads at the start and check after the test that there are no new threads (there may be some expected ones which are okay) 您甚至可能希望在开始时拍摄正在运行的线程的快照,并在测试后检查没有新线程(可能有一些预期的线程没问题)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM