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



我正在尝试模拟函数'privateMethod'以返回"新价值";而不是";原始价值";。函数"callPrivateMethod"的目的只是调用和测试私有方法。

class MyClass {
private fun privateMethod(): String = "Original value"
fun callPrivateMethod() = privateMethod()
}

我在嘲笑多个来源中描述的私有方法。由于某种原因,该方法第一次返回null。它只在第二次正确返回"0"时工作;新价值";。

@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"(。我还尝试使用方法(…(函数,而不是将方法作为字符串传递。我尝试更新junit和powermockito依赖关系。

我发现了问题。我使用的是Mockitospy函数,而不是PowerMockitospy函数。

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"

最新更新