如何在 Kotlin 中模拟顶级扩展类函数?

问题描述 投票:0回答:1

我有一些 Kotlin 代码,在 3P 提供的类 (

anExtensionMethod
) 上定义了扩展函数 (
RdsClient
):

// MyLib.kt

import software.amazon.awssdk.services.rds.RdsClient
public fun RdsClient.anExtensionMethod(): String {
  return "hi"
}

在单元测试中,我想模拟

anExtensionMethod
,就像这样:

// MyLibTest.kt
import com.tecton.orchestrator.monitoring.anExtensionMethod
  @Test
  fun testIt() {
    var mockRdsClient_: RdsClient = mock { on { anExtensionMethod() } doReturn "bob" }
    ...

在运行时,我遇到

org.mockito.exceptions.misusing.MissingMethodInvocationException
失败:

1) testAllMetricsAreCollected(...)
org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

        at com.tecton.orchestrator.monitoring.RDSMetricsCollectorModuleTest.testIt(MyTest.kt:..)

FAILURES!!!
Tests run: 1,  Failures: 1

我发现了很多使用

mockkStatic
的建议,但到目前为止,该函数的所有排列都没有解决该问题。我怀疑这种特殊情况存在一些细微差别:要模拟的类来自 3P 库;扩展方法是通过顶级函数定义的。感谢任何有关解决此模拟错误的指示!

kotlin mockito
1个回答
0
投票

已确认:我的

mockkStatic
调用有点混乱。事实证明
mockkStatic("com.tecton.orchestrator.lib.rds.RdsHelperKt")
有效(这是我定义的扩展函数的文件的包路径,加上
Kt
后缀)。

© www.soinside.com 2019 - 2024. All rights reserved.