Kotlin MockK declaring mocks in companion objects

124 Views Asked by At

I was writing some unit tests in MockK and had a lot of test cases while also sharing some mock variables between tests, so I thought I could declare the mocks in the companion object to not clutter the tests.

Example assuming I used 'mockObject' a lot and the tested class returns 'mockObject':

companion object {
    val mockObject = mockk<TestClass> {
       every { property } returns "test"
    }
}

When I ran each test, it passed. However, when I ran the test suite all at once, various tests started failing and saying 'No answer for TestClass.property', even though I had clearAllMocks() done after each test. After a lot of headache, I finally figured out that moving the mock out of the companion object and putting it directly in the test fixed my issues. I was wondering why this is the case.

0

There are 0 best solutions below