簡體   English   中英

Mocking 使用 PowerMockito 的私有方法只能從第二個方法調用開始

[英]Mocking private method with PowerMockito only works starting with second method call

我正在嘗試模擬 function 'privateMethod' 以返回“新值”而不是“原始值”。 function 'callPrivateMethod' 的目的只是為了調用和測試私有方法。

class MyClass {

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

    fun callPrivateMethod() = privateMethod()
}

我是 mocking 多個來源中描述的私有方法。 出於某種原因,該方法第一次返回 null。它僅在第二次正確返回“新值”時起作用。

@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”)。 我還嘗試使用方法 (...) function 而不是將方法作為字符串傳遞。 我嘗試更新 junit 和 powermockito 依賴項。

我發現了問題。 我使用的是來自Mockitospy function 而不是來自PowerMockitospy function。

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM