如何使 JUnit 的行为与从命令行运行的 Java 相同
我注意到,当单元测试退出时,所有生成的线程都会自动终止,这与从命令行运行的java程序有很大不同。在命令行中,直到所有非守护线程退出后,程序才会退出。
如何使用 jUnit 测试涉及生成线程的情况?
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. In the command line, the program does not exit until all the non deamon threads exit.
How to test the case involving spawned thread using jUnit?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您正在测试的方法返回对其创建的线程的引用,则加入该线程。如果没有,请创建自己的线程来调用被测试的方法并加入该方法。
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.
我建议您将单元测试 shutdown() 其组件,以便它返回到测试开始之前的状态。这在运行的系统中实际上可能不是必需的,但它允许您多次运行多个测试。
您甚至可能想在开始时拍摄正在运行的线程的快照,并在测试后检查是否有新线程(可能有一些预期的线程,这没有问题)
I would suggest you make your unit test shutdown() its components such that it returns to the state before the test started. 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)