模拟创作中的Mockito模拟创作

时间:2017-08-02 14:14:31

标签: mockito kotlin

我得到的错误是org.mockito.exceptions.misusing.UnfinishedStubbingException,其中一个可能的原因是"你正在查看另一个模拟内部的行为然后返回'然后返回'指令如果完成"。

    val mockHttpHandlerContext = mock<HttpHandlerContext>().let {
        whenever(it.request).thenReturn(mock<HttpRequest>().let {
            whenever(it.queryParameters).thenReturn(mapOf(
                    "itype" to listOf("msisdn"),
                    "uid" to listOf(inputMsisdn)
            ))
            it
        })
        whenever(it.scope()).thenReturn(ProcessingScope.of(Timings("test", 1000L)))
        it
    }

是摆脱嵌套模拟创建的唯一解决方案吗?这会让代码更难理解,也许有一个已知的解决方法?

代码片段是Kotlin。

1 个答案:

答案 0 :(得分:1)

根据命名判断,我假设您正在使用nhaarman/Mockito-Kotlin

Mockito是有状态的,你必须按顺序创建模拟,但有一些方法可以翻转评估顺序。例如,

val mockHttpHandlerContext2 = mock<HttpHandlerContext>() {
    mock<HttpRequest>() {
        on { queryParameters }.thenReturn(mapOf(
                "itype" to listOf("msisdn"),
                "uid" to listOf(inputMsisdn)
        ))
    }.let { on { request }.thenReturn(it) }
    on { scope() }.thenReturn(ProcessingScope.of(Timings("test", 1000L)))
}

我正在利用mock()接收器的KStubbing<T>重载,但重要的是在使用.let在存根上设置它之前先创建内部模拟。< / p>

另一种选择是使用.thenAnswer推迟创建内部模拟,直到调用stubbed方法为止。

val mockHttpHandlerContext = mock<HttpHandlerContext>() {
    on { request }.thenAnswer {
        mock<HttpRequest>() {
            on { queryParameters }.thenReturn(mapOf(
                    "itype" to listOf("msisdn"),
                    "uid" to listOf(inputMsisdn)
            ))
        }
    }
    on { scope() }.thenReturn((ProcessingScope.of(Timings("test", 1000L)))
}

请注意,每次调用stubbed方法时,这都会创建一个新的模拟。在某些情况下可能不太可取,例如,如果您想对内部模拟执行验证。

相关问题