JUnit 终止子线程 [英] JUnit terminates child threads

查看:51
本文介绍了JUnit 终止子线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我测试一个创建子线程的方法的执行时,JUnit 测试在子线程之前结束并杀死它.

When I test the execution of a method that creates a child thread, the JUnit test ends before the child thread and kills it.

如何强制 JUnit 等待子线程完成其执行?

How do I force JUnit to wait for the child thread to complete its execution?

推荐答案

阅读问题和一些评论后,您似乎需要一种用于单元测试异步操作的技术.doSomething() 立即返回,但您希望测试代码等待其完成,然后进行一些验证.

After reading the question and some comments, it seems that what you need is a technique for unit testing asynchronous operations. doSomething() returns immediately, but you want the test code to wait for its completion, and then do some validations.

问题是测试不知道调用产生的线程,所以显然它没有办法等待它们.人们可以想到许多复杂(并且可能有缺陷)的方法来解决这个问题,但在我看来,这里存在一个设计问题.单元测试应该模拟某个 API 的客户端,并且不应该对实现做任何假设;它应该只测试 API 及其文档所反映的功能.因此,我会避免尝试检测和跟踪异步调用创建的线程.相反,如果需要,我会改进测试类的 API.异步调用所属的类应该提供一些检测终止的机制.我可以想到 3 种方法,但可能还有更多:

The problem is that the test is not aware of the threads being spawned by the call, so apparently it has no means of waiting for them. One can think of many sophisticated (and probably flawed) ways to solve this, but in my opinion there is a design problem here. A unit test should simulate a client of some API, and it should not assume anything about the implementation; It should only test functionality, as reflected by the API and its documentation. Therefore, I would avoid trying to detect and track the threads created by the async call. Instead, I would improve the API of the tested class, if needed. The class where the async call belongs to should provide some mechanism for detecting termination. I can think of 3 ways, but there are probably more:

  1. 允许注册一个监听器,一旦操作完成就会收到通知

  1. Allow registering a listener that gets notified once the operation is completed

提供操作的同步版本.实现可以调用异步版本,然后阻塞直到完成.如果类不应该公开这样的方法,则可以将其可见性降低到包保护,以便测试可以访问它.

Providing a synchronous version of the operation. The implementation can call the async version, and then block until completion. If the class should not be exposing such a method, its visibility can be reduced to package protected, so that the test can access it.

在一些可见对象上使用等待通知模式.

Using the wait-notify pattern, on some visible object.

如果类没有提供这样的机制,那么它就不是真正可测试的,更糟糕​​的是,它可能也不是很可重用.

If the class provides no such mechanism, then it is not really testable, and worse, it is probably not very reusable either.

这篇关于JUnit 终止子线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆