我正试着在Kotlin身上测试这个:
verify(myInterface).doSomething(argumentCaptor.capture())
capture.value.invoke(0L)其中doSomething是:
doSomething((Long) -> Unit)如何为此创建一个ArgumentCaptor?现在我正在做这个
inline fun <reified T : Any> argumentCaptor() = ArgumentCaptor.forClass(T::class.java)!!
val captor = argumentCaptor<(Long) -> Unit>()
verify(mainApiInterface!!).downloadUserProfilePicture(captor.capture())
captor.value.invoke(0L)但是我得到了java.lang.IllegalStateException: captor.capture()必须不是null
我也尝试过集成mockito-kotlin,但是我得到了一个PowerMockito错误:
在org.mockito.internal.MockitoCore的类层次结构中找不到名为"reported“的实例字段。
发布于 2017-01-30 23:16:04
像这样使用莫奇托-科特林似乎很有效:
val myService = mock<MyInterface>()
myService.doSomething {
println(it)
}
verify(myService).doSomething(capture { function ->
function.invoke(123)
})编辑:删除不必要的argumentCaptor<(Long) -> Unit>().apply {} -它没有使用
发布于 2022-04-06 19:33:25
与kotlin 1.3.72和com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0一样,以下内容对我来说很好:
通过val captor = argumentCaptor<() -> Unit>()创建一个参数捕获器,并在其上调用captor.capture()。
对于带有nullableArgumentCaptor()的可空捕获者,也有一个变体
下面的单元测试捕获了() -> Unit类型的lambda,它给出了diff.open()。若要在运行时捕获它,则使用captor.capture()
// given
val onClose = argumentCaptor<() -> Unit>()
// when
diff.open(file, serialized) { onDiffClosed(clusterResource, documentBeforeDiff) }
// then
verify(diff).open(any(), any(), onClose.capture())mockito的nhaarman包装器为mockito类KArgumentCaptor创建一个包装器ArgumentCaptor。nhaarman包装器通过创建一个实例来修复您的错误,而不是像mockito中的null那样。
https://stackoverflow.com/questions/41945675
复制相似问题