等待 JUnit 测试用例中测试的代码生成的所有线程

发布于 2024-09-15 02:10:43 字数 308 浏览 5 评论 0原文

如何确保在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

牵你的手,一向走下去 2024-09-22 02:10:43

真正的问题是,如何在非测试代码中处理这种情况? method() 的 API 向其调用者保证什么时候设置 result.value

在编写测试时请牢记这一点 - 目的是断言类及其方法的行为如其所宣传的那样。有时,弄清楚广告中的界面是什么可能是挑战的一半。

在这种情况下,我强烈建议您的 Result 对象表现得像 Future 一样,因为它的 get() 方法会阻塞,直到结果可用。 (或者,给它一个 waitFor() 方法或类似方法)。

如果您的方法不提供任何特定的保证或阻止调用,那么您在测试中真正可以做的就是在循环中每x秒检查一次值,将测试中的 @Timeout 以确保该值设置在“合理”的时间内。但这也是客户端所能做的,所以

  1. 这是一个非常有效的测试;
  2. 它强调了该界面对于客户来说不太有用,修改它将是一个好主意。

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.

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

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. it's a very valid test;
  2. it highlights that the interface isn't very usable for clients and modifying it would be a nice idea.
愿与i 2024-09-22 02:10:43

我建议你在method()中调用多线程实例上的Thread#join,按照这样,所有子线程都完成了。

I suggest you invoke the Thread#join on multiple threads instances in method(),follow this way,all sub threads are completed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文