kotlinjunitmockk

Kotlin junit MockK runner


I'm trying to write unit tests using Kotlin and MockK framework. If tests are written using junit 5 framework it's possible to run them using MockKExtension.

@ExtendWith(MockKExtension::class)

But for junit 4 tests is there a MockK runner? Like:

@RunWith(....)

Without such runner it's required to initialize mocks manually.

private val a: A = mockK()

Is it possible to initialize kotlin mocks using annotation with junit 4?

@MockK
private lateinit var a: A

Solution

  • Quick answer is no.

    BUT. It's very simple to use MockK with JUnit 4:

    All you need is code like this:

    class CarTest {
      @MockK
      lateinit var car1: Car
      @Before
      fun setUp() = MockKAnnotations.init(this, relaxUnitFun = true) // turn relaxUnitFun on for all mocks
      // And so on…
    

    BTW, it's not hand-crafted example, it's from official documentation