等待我在JUnit测试用例中测试的代码生成的所有线程 [英] Waiting for all threads spawned by my code under test in JUnit test case

查看:191
本文介绍了等待我在JUnit测试用例中测试的代码生成的所有线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JUnit测试用例中确保被测试方法直接/间接生成的所有线程都是通过该作业完成的,这样我才能断言最终结果?

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


推荐答案

真正的问题是,如何你在非测试代码中处理这种情况吗? 方法()的API如何保证其调用者何时会设置 result.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 when result.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.

在这种情况下,我强烈建议你的结果对象的行为类似于 Future ,因为它的 get()方法会阻塞,直到结果为止是可用的。 (或者,给它一个 waitFor()方法或类似方法)。

In a situation like this, I would strongly recommend that your Result object behave like a Future, in that its get() method blocks until the result is available. (Alternatively, give it a waitFor() method or similar).

如果你的方法没有提供任何特定的保证或阻止调用,你在测试中真正做的就是在循环中每隔 x 秒检查一次值,放一个 @测试时超时以确保在合理时间内设置该值。但这也是客户能够做到的,所以

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


  1. 这是一个非常有效的测试;

  2. 它突出显示界面对客户端不是很有用,修改它会是一个不错的主意。

这篇关于等待我在JUnit测试用例中测试的代码生成的所有线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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