Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

java - JUnit terminates child threads

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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. Allow registering a listener that gets notified once the operation is completed

  2. 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.

  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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...