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

查看:106
本文介绍了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 asynch call. Instead, I would improve the API of the tested class, if needed. The class where the asynch 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

2)提供操作的同步版本。该实现可以调用异步版本,然后阻塞直到完成。如果类不应该暴露这样的方法,它的可见性可以减少到包保护,以便测试可以访问它。

2) Providing a synchronous version of the operation. The implementation can call the asynch 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.

3)使用wait-notify一些可见对象上的模式。

3) 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天全站免登陆