Skip to main content

Thread safety

Mokkery 3

Mocks created with Mokkery 3 are thread-safe. You can configure them, verify interactions, and invoke their methods from multiple threads without additional synchronization. Just make sure that any defined matcher/answer does not perform any not synchronized side effects. Example below shows this kind of side effect:

var x: Int = 0
every { mock.getAndIncrement() } calls { x++ }

To synchronize it, you can use atomic-fu:

var x = atomic<Int>(0)
every { mock.getAndIncrement() } calls { x.getAndIncrement() }

Before Mokkery 3

Mocks created using Mokkery 1 & 2 are generally considered "thread safe" in the context of their usage in a multithreaded environment. It means that calling methods on configured mock from different threads is safe.

However, configuration operations (e.g. every, everySuspend) and verification operations (e.g. verify, verifySuspend) are not thread-safe. These operations should be performed from a single thread!

Also, make sure that any defined matcher/answer does not perform any not synchronized side effects. Example below shows this kind of side effect:

var x: Int = 0
every { mock.getAndIncrement() } calls { x++ }

To synchronize it, you can use atomic-fu:

var x = atomic<Int>(0)
every { mock.getAndIncrement() } calls { x.getAndIncrement() }