mockkkotest

Kotest parallelism with Mockk


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?


Solution

  • 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