Home > Blockchain >  Mocking private method with PowerMockito only works starting with second method call
Mocking private method with PowerMockito only works starting with second method call

Time:04-08

I'm trying to mock the function 'privateMethod' to return "New value" instead of "Original value". The purpose of the function 'callPrivateMethod' is just to call and test the private method.

class MyClass {

    private fun privateMethod(): String = "Original value"

    fun callPrivateMethod() = privateMethod()
}

I'm mocking the private method as described in multiple sources. For some reason, for the first time, the method returns null. It only works the second time, when it correctly returns "New value".

@RunWith(PowerMockRunner::class)
@PowerMockRunnerDelegate(JUnit4::class)
@PrepareForTest(MyClass::class)
class MyClassTest {

    @Test
    fun myTest() {
        val newValue = "New value"
        val myClass = MyClass()

        val mySpy = spy(myClass)
        PowerMockito.doReturn(newValue).`when`(mySpy, "privateMethod")

        val v1 = mySpy.callPrivateMethod() // v1 == null
        val v2 = mySpy.callPrivateMethod() // v2 == "New value"

        // assertEquals(newValue, v1) // commented because it would fail
        assertEquals(newValue, v2) // this works
    }
}

I included the neccesary annotations (also tried without the 'PowerMockRunnerDelegate'). I also tried using the method(...) function instead of passing the method as a string. I tried updating the junit and powermockito dependencies.

CodePudding user response:

I found the problem. I was using the spy function from Mockito instead of the spy function from PowerMockito.

val mySpy = PowerMockito.spy(myClass)

Also, here are my dependencies. Mixing them in a wrong way causes problems because there are compatibility issues.

testImplementation "junit:junit:4.13.1"

testImplementation "androidx.test:core:1.3.0"

testImplementation "androidx.arch.core:core-testing:2.1.0"

testImplementation "org.mockito:mockito-inline:3.3.3"

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"

testImplementation "org.powermock:powermock-module-junit4:2.0.2"

testImplementation "org.powermock:powermock-core:2.0.2"

testImplementation "org.powermock:powermock-api-mockito2:2.0.2"

  • Related