Testing 如何在Kotlin中模拟和验证Lambda表达式?
在Kotlin(和Java8)中,我们可以使用Lambda表达式删除样板回调接口。比如说,Testing 如何在Kotlin中模拟和验证Lambda表达式?,testing,lambda,kotlin,mockito,Testing,Lambda,Kotlin,Mockito,在Kotlin(和Java8)中,我们可以使用Lambda表达式删除样板回调接口。比如说, data class Profile(val name: String) interface ProfileCallback { fun onSuccess(profile: Profile) } class ProfileRepository(val callback: ProfileCallback) { fun getProfile() { // do calculation
data class Profile(val name: String)
interface ProfileCallback {
fun onSuccess(profile: Profile)
}
class ProfileRepository(val callback: ProfileCallback) {
fun getProfile() {
// do calculation
callback.onSuccess(Profile("name"))
}
}
我们可以将removeProfileCallback
更改为Kotlin的Lambda:
class ProfileRepository(val callback: (Profile) -> Unit) {
fun getProfile() {
// do calculation
callback(Profile("name"))
}
}
这很好,但我不确定如何模拟并验证该函数。我有
试过像这样使用Mockito吗
@Mock
lateinit var profileCallback: (Profile) -> Unit
@Test
fun test() {
// this wouldn't work
Mockito.verify(profileCallback).invoke(any())
}
但它抛出了一个例外:
org.mockito.exceptions.base.MockitoException:ClassCastException
创建要模拟的mockito mock:类时发生:
“kotlin.jvm.functions.Function1”,由类加载器加载:
'sun.misc.Launcher$AppClassLoader@7852e922"
如何在Kotlin中模拟和验证Lambda表达式?甚至可能吗?以下是使用
mockito kotlin
实现这一点的示例:
给定的存储库类
class ProfileRepository(val callback: (Int) -> Unit) {
fun getProfile() {
// do calculation
callback(1)
}
}
使用mockito kotlin
lib-您可以像这样编写测试模拟lambda:
@Test
fun test() {
val callbackMock: (Int) -> Unit = mock()
val profileRepository = ProfileRepository(callbackMock)
profileRepository.getProfile()
argumentCaptor<Int>().apply {
verify(callbackMock, times(1)).invoke(capture())
assertEquals(1, firstValue)
}
}
@测试
趣味测试(){
val callbackMock:(Int)->Unit=mock()
val profileRepository=profileRepository(callbackMock)
profileRepository.getProfile()
argumentCaptor().apply{
验证(callbackMock,times(1)).invoke(capture())
资产质量(1,第一个值)
}
}
trymockito kotlin
lib,如果您有时间,请查看Hi@OleksandrPapchenko,您是否会将答案与如何使用它的示例代码一起发布?