Skip to content

MockK: Testing private methods using spyK

Devrath edited this page Mar 2, 2024 · 1 revision
  • MockK is a framework that is used to create mocks, stub behaviors, and verify interactions with your tests.
  • And when it comes to testing private methods we can use spyK.

Test

class PrivateClassUnderDemoTest {

    @Test
    fun testPrivateMethod() {

        // <--------------------> Arrange <-------------------->
        val resultToCheck = "Mocked Private result!"
        val privateMethodName = "privateMethod"

        // <--------------------> Act <------------------------>
        // Create a spy of our class
        val ourClass = spyk( PrivateClassUnderDemo() )
        // Stub a private method to return a value
        every { ourClass[privateMethodName]() } returns resultToCheck
        // Call the public method, That will invoke the public method
        val result = ourClass.publicMethod()

        // <--------------------> Assert <-------------------->
        // Assert the result
        assertEquals(resultToCheck, result)

    }

}

Code

class PrivateClassUnderDemo {

    private fun privateMethod(): String {
        return "Hello, Private!"
    }

    fun publicMethod(): String {
        return privateMethod()
    }

}