(科特林)Mockito 帮助程序,用于模拟具有上下文的方法

(kotlin) Mockito helper to mock a method with a context

提问人:Rolintocour 提问时间:10/31/2023 更新时间:10/31/2023 访问量:26

问:

我使用 mockito-kotlin,它非常适合编写这种代码,并且是一个挂起函数:myMethod

mock(MyClass) {
  onBlocking { myMethod() }.doReturn("hi")
}

现在我想在 myMethod 中使用一个上下文接收器,比如

context(MyContext)
suspend fun myMethod() {
 ...
}

模拟定义现在不再编译器,因为它需要上下文,所以我可以这样做:

mock(MyClass) {
  onBlocking { 
    with(MyContext) {
      myMethod() 
    }
  }.doReturn("hi")
}

这很好用,但我在 50 个地方有相同的代码段,所以我想定义一个自动提供上下文的帮助程序方法。我能达到的最好的效果是(这主要是原始方法的复制粘贴):onBlocking

fun <T : Any, R> KStubbing<T>.onBlockingContext(
    m: suspend context(MyContext) T.() -> R
): OngoingStubbing<R> {
    val context = any<MyContext>()
    return runBlocking {
        with(context) {
            Mockito.`when`(m([email protected]))
        }
    }
}

但是,在运行时,我出现以下错误:

java.lang.ClassCastException: class MyClass cannot be cast to class MyContext (MyClass and MyContext are in unnamed module of loader 'app')

知道我如何让它工作 - 或者另一种将代码放在一起的方法吗?

Kotlin mockito kotlin-dsl mockito-kotlin

评论


答: 暂无答案