Skip to content

MockK: Check if a function is invoked

Devrath edited this page Mar 2, 2024 · 2 revisions
  • Assume we have a class that we are testing, We call it SUT
  • Here we need to check if the function is invoked or not in a certain scenario

Test

class FunctionInvokedDemo {

    fun myMethod() {
        println("Hello, World!")
    }

}

Code

class FunctionInvokedDemoTest {

    @Test
    fun testMethodInvocation() {
        // <--------------------> Arrange <-------------------->
        // SUT
        val sut = mockk<FunctionInvokedDemo>()
        // Tell the SUT with Mockk that the method is invoked functionality
        every { sut.myMethod() } returns Unit
        // <--------------------> Act <------------------------>
        sut.myMethod()
        sut.myMethod()
        // <--------------------> Assert <--------------------->
        verify(exactly = 2) { sut.myMethod() }
    }

}