How do I ensure in a JUnit test case, that all the the threads spawned directly/indirectly by the method under test are done with there job, so that I can assert the final result?
@Test
public void testMethod() {
Result result=method();// may spawn multiple threads to set result.value
Assert.assertTrue(result.getValue()==4); //should execute only after result.value is set to its final value.
}
The real question is, how do you deal with this case in your non-test code? What does the API of
method()guarantee to its callers about whenresult.valuewill be set?Bear that in mind strongly when writing tests – the purpose is to assert that the class and its methods behave as they advertise. Sometimes, working out what the advertised interface is can be half of the challenge.
In a situation like this, I would strongly recommend that your
Resultobject behave like aFuture, in that itsget()method blocks until the result is available. (Alternatively, give it awaitFor()method or similar).If your method doesn’t provide any specific guarantees or blocking calls, all you can really do in the test is to keep checking the value every x seconds in a loop, putting a
@Timeouton the test to ensure that the value is set in a “reasonable” time. But this is all a client would be able to do too, so