io.mockk.MockKException:无法匹配 SignedCall 的模拟签名

Ham*_*ari 5 android code-coverage kotlin mockk

我在运行模拟测试(使用 mockK 和 Kotlin)时遇到问题。

我进行了一些工作单元测试。昨天我正在测试我实现的功能。但每当我尝试运行测试时,就会出现此异常:

io.mockk.MockKException: Failed matching mocking signature for
SignedCall(retValue=, isRetValueMock=true, retType=class kotlin.Unit, self=Observer(#1), method=onChanged(Any), args=[kotlin.Unit], invocationStr=Observer(#1).onChanged(kotlin.Unit))
left matchers: [any()]

    at io.mockk.impl.recording.SignatureMatcherDetector.detect(SignatureMatcherDetector.kt:99)
    at io.mockk.impl.recording.states.RecordingState.signMatchers(RecordingState.kt:39)
    at io.mockk.impl.recording.states.RecordingState.round(RecordingState.kt:31)
Run Code Online (Sandbox Code Playgroud)

此外,如果我尝试运行覆盖范围的测试,android studio 会记录这些错误:

[2021.08.24 12:05:30] (Coverage): Error during class instrumentation: kotlin.text.Regex: java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 14
[2021.08.24 12:05:31] (Coverage): Error during class instrumentation: kotlin.text.StringsKt___StringsKt: java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 14
[2021.08.24 12:05:31] (Coverage): Error during class instrumentation: kotlin.text.StringsKt__StringsKt: java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 14
[2021.08.24 12:05:31] (Coverage): Error during class instrumentation: kotlin.text.StringsKt__StringsJVMKt: java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 14
[2021.08.24 12:05:31] (Coverage): Error during class instrumentation: kotlin.text.StringsKt__StringNumberConversionsJVMKt: java.lang.StringIndexOutOfBoundsException: begin 0, end -1, length 14
Run Code Online (Sandbox Code Playgroud)

代码只是一个简单的调用检查,下面是一个例子:

 @Test
    fun onLoginButtonPressed() {
        // Arrange
        val tObserver: Observer<Unit> = mockk(relaxUnitFun = true)
        viewModel.launchLoginScreenEvent.observeForever(tObserver)

        // Act
        viewModel.onLoginButtonPressed()

        // Assert
        verify(exactly = 1) { tObserver.onChanged(any()) }
    }
Run Code Online (Sandbox Code Playgroud)

我不知道这两个问题是否相关,但在我的案例中它们同时出现。

Kotlin 版本:1.4.31 Android Studio:4.2(从北极狐回滚)

Vic*_*ira 3

我偶尔遇到的可能情况:

  1. 您正在验证一个对象而不是模拟/间谍

  2. Internally onChanged might be hitting an inlined function or in other cases is the inlined function itself

  3. The any() object being requested has an Abstract Type argument.

  • (i.e. MyObject<T> which is the same as calling any<MyObject<T>>())

Solutions

  1. Make sure to properly call a mock or spied object
  2. No way to solve
  3. If possible, adapt your production code to directly access T.
  • (i.e. verify { mock.method(any<T>()) })