使用 PowerMockito 模拟私有方法只能从第二个方法调用开始

Mocking private method with PowerMockito only works starting with second method call

我正在尝试将函数 'privateMethod' 模拟为 return“新值”而不是“原始值”。函数'callPrivateMethod'的目的只是为了调用和测试私有方法。

class MyClass {

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

    fun callPrivateMethod() = privateMethod()
}

我正在模拟多个来源中描述的私有方法。出于某种原因,方法 return 第一次为空。它仅在第二次正确时起作用returns“新值”。

@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
    }
}

我包括了必要的注释(也试过没有 'PowerMockRunnerDelegate')。我还尝试使用 method(...) 函数而不是将方法作为字符串传递。我尝试更新 junit 和 powermockito 依赖项。

我发现了问题。我使用的是 Mockito 中的 spy 函数,而不是 PowerMockito 中的 spy 函数。

val mySpy = PowerMockito.spy(myClass)

此外,这是我的依赖项。以错误的方式混合它们会导致问题,因为存在兼容性问题。

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"