等待 JUnit 测试用例中测试的代码生成的所有线程
如何确保在 JUnit 测试用例中,由被测方法直接/间接生成的所有线程都已完成该作业,以便我可以断言最终结果?
@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.
}
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.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
真正的问题是,如何在非测试代码中处理这种情况?
method()
的 API 向其调用者保证什么时候设置result.value
?在编写测试时请牢记这一点 - 目的是断言类及其方法的行为如其所宣传的那样。有时,弄清楚广告中的界面是什么可能是挑战的一半。
在这种情况下,我强烈建议您的
Result
对象表现得像Future
一样,因为它的get()
方法会阻塞,直到结果可用。 (或者,给它一个waitFor()
方法或类似方法)。如果您的方法不提供任何特定的保证或阻止调用,那么您在测试中真正可以做的就是在循环中每x秒检查一次值,将测试中的
@Timeout
以确保该值设置在“合理”的时间内。但这也是客户端所能做的,所以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.value
will 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
Result
object 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
@Timeout
on 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我建议你在method()中调用多线程实例上的Thread#join,按照这样,所有子线程都完成了。
I suggest you invoke the Thread#join on multiple threads instances in method(),follow this way,all sub threads are completed.