简体   繁体   English

Java Mockito 模拟方法调用线程安全吗?

[英]Are Java Mockito mocked method invocations thread safe?

I am writing unit tests that test the thread safety of individual Java classes.我正在编写单元测试来测试单个 Java 类的线程安全性。 I use Mocktio to set up the tests and verify the interactions in a multithreaded environment are done as per the expectations, and threads do not interfere with business expectations.我使用 Mocktio 来设置测试并验证多线程环境中的交互是否按预期完成,并且线程不会干扰业务预期。

Are Mockito mocks thread-safe in that context? Mockito 在这种情况下模拟线程安全吗? Can the mocked methods be called by many threads and the invocations will be counted correctly?模拟方法是否可以被多个线程调用并且调用会被正确计算?

Yes, they are.对,他们是。 Quoting mockito documentation .引用mockito 文档

(...) you can let multiple threads call methods on a shared mock to test in concurrent conditions. (...) 您可以让多个线程调用共享模拟上的方法以在并发条件下进行测试。

Not exactly.不完全是。

Calling a method in parallel threads and counting times in Mockito.verify(..) may yield different results in each run.在并行线程中调用方法并在Mockito.verify(..) 中计算时间可能会在每次运行中产生不同的结果。

Suppose we're testing the following call:假设我们正在测试以下调用:

...
someListOfSize20.parallelStream().forEach(testedObject::methodToBeTested);
...

And try to verify:并尝试验证:

Mockito.verify(testedObject, times(20)).methodToBeTested(any());

This tends to fail with different numbers of invocations on each run.这往往会因每次运行的调用次数不同而失败。

Here's the (still open) ticket about this: https://github.com/mockito/mockito/issues/1037这是关于这个的(仍然开放的)票: https : //github.com/mockito/mockito/issues/1037

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM