如何编写多线程单元测试?
我想知道是否有一些单元测试框架能够轻松编写多线程测试?
我会想象这样的事情: n个线程同时调用一个特殊的测试方法m次。所有测试线程完成后,将调用应验证某些约束的断言方法。
我当前的方法是在 junit 测试方法中创建 Thread 对象,在每个 run() 方法中手动循环真实的测试用例,等待所有线程,然后验证断言。但是使用这个,我为每个测试都有一个大的样板代码块。
你有什么经历?
I'd like to know if there are some unit testing frameworks which are capable of writing multi-threaded tests easily?
I would imagine something like:
invoke a special test method by n threads at the same time for m times. After all test threads finished, an assertion method where some constraints should be validated would be invoked.
My current approach is to create Thread objects inside a junit test method, loop manually the real test cases inside each run() method, wait for all threads and then validate the assertions. But using this, I have a large boilerplate code block for each test.
What are your experiences?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有 ConTest,还有 GroboUtils。
我多年前就使用过 GroboUtils,它完成了这项工作。 ConTest 较新,并且是我现在首选的起点,因为该仪器不只是依赖于反复试验,而是强制线程的特定交错,从而提供确定性测试。相比之下,GroboUtils MultiThreadedTestRunner 只是运行测试并希望调度程序产生导致线程错误出现的交错。
编辑:另请参阅 ConcuTest 它也强制交错并且是免费的。
There is ConTest, and also GroboUtils.
I've used GroboUtils many years ago, and it did the job. ConTest is newer, and would be my preferred starting point now, since rather than just relying on trial and error, the instrumentation forces specific interleavings of the threads, providing a deterministic test. In contrast, GroboUtils MultiThreadedTestRunner simply runs the tests and hopes the scheduler produces an interleaving that causes the thread bug to appear.
EDIT: See also ConcuTest which also forces interleavings and is free.
还有 FindBugs 出名的 Bill Pugh 的 MultithreadedTC。
There is also MultithreadedTC by Bill Pugh of FindBugs fame.
仅使用并发库就可以简化您的代码。您可以将样板代码转变为一种方法。
像这样的东西
Just using the concurrency libraries would simplify your code. You can turn your boiler plate code into one method.
Something like
http://www.awaitility.org/ 是用于异步代码单元测试的最现代的断言测试。
http://www.awaitility.org/ is the most modern assert testing for async code unit testing.