2

So I've been using kotest in combination with mockk, but I encountered an issue when switching from single thread mode to multiple by adding this to ProjectConfig class:

override fun parallelism(): Int = Runtime.getRuntime().availableProcessors()

If I run in single mode. All of my tests pass, but just as I switch to parallelism, some of them, that use mocks, start failing.

I have methods all over like:

override fun afterTest(testCase: TestCase, result: TestResult) {
    clearAllMocks()
}

So I imagine methods like these could be causing my mocks to fail by clearing all mock data before verify block.

Is there a way to force tests on different threads use their own Mockk instances and force clearAllMocks() method to only clear mocks on calling thread? If not, what other code practices could help with these issues?

LeoColman
  • 6,950
  • 7
  • 34
  • 63
SMGhost
  • 3,867
  • 6
  • 38
  • 68
  • Unfortunately, I don't believe `mockk` supports multi-threading and `clearAllMockks`. [A very similar issue](https://github.com/mockk/mockk/issues/301) came up for Mockk and Spek early in 2019, and the solution was just "You can't use `clearAllMocks` with parallelism" – LeoColman Jan 10 '20 at 23:42
  • Perhaps you can clear individual mocks at `afterTest` and clear them one by one? – LeoColman Jan 10 '20 at 23:43
  • @Kerooker, yes, I've ended up replacing clearAllMockks with clearMocks(mock1, mock2, mock3, etc..) and it seems to work now. Please leave a proper answer so I could mark it as accepted:) – SMGhost Jan 12 '20 at 04:40

1 Answers1

3

According to this issue in mockk repository, related to another test framework, clearAllMocks cannot be run parallelly.

In case your tests get execute in parallel you are not able to use clearAllMocks

oleksiyp commented on May 15, 2019

This is likely due to the way that mockk keeps things in memory, and clearAllMocks can't correctly (and perhaps shouldn't) handle race conditions very well.

What you can do is clear every instance mock individually with clearMocks:

override fun afterTest(testCase: TestCase, result: TestResult) {
    clearMocks(mockedInstance1, mockedInstance2, mockedInstance3)
}

And it should work when running parallelly

LeoColman
  • 6,950
  • 7
  • 34
  • 63