Mockito模拟创作里面的模拟创作

我得到的错误是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。

根据命名来判断,我假设你正在使用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))) } 

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

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

 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))) } 

请注意,每次调用存根方法时,都会创建一个新的模拟对象。 在某些情况下,如果要对内部模拟执行验证,可能不太合乎需要。