Are Java Mockito mocked method invocations thread safe?

4.5k views Asked by At

I am writing unit tests that test the thread safety of individual Java classes. 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.

Are Mockito mocks thread-safe in that context? Can the mocked methods be called by many threads and the invocations will be counted correctly?

2

There are 2 answers

0
Wojtek On BEST ANSWER

Yes, they are. Quoting mockito documentation.

(...) you can let multiple threads call methods on a shared mock to test in concurrent conditions.

2
Yigit On

Not exactly.

Calling a method in parallel threads and counting times in Mockito.verify(..) may yield different results in each run.

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