Kotlin Mockito始终返回作为参数传递的对象 [英] Kotlin Mockito always return object passed as an argument

查看:119
本文介绍了Kotlin Mockito始终返回作为参数传递的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以这种方式在模拟对象上使用Mockito,使其始终应返回作为参数传入的完全相同的对象.我尝试这样做:

I am trying to use Mockito on my mocked object in such a way that it should always return the very same object that was passed in as an argument. I tried it do to it like so:

private val dal = mockk<UserDal> {
    Mockito.`when`(insert(any())).thenAnswer { doAnswer { i -> i.arguments[0] } }
}

但是,此行始终失败:

io.mockk.MockKException: no answer found for: UserDal(#1).insert(null)

insert(user: User)方法不接受null作为参数(显然User不是可为空的类型).

The insert(user: User) method doesn't take in null as an argument (obviously User is not a nullable type).

如何使insert()方法始终返回作为参数接收的同一对象?

How can I make the insert() method always return the same object that it received as an argument?

推荐答案

在使用 MockK 时,请勿使用 Mockito .

仅使用 MockK ,您可以通过以下方式实现相同的目标:

Only using MockK you can achieve the same with:

val dal = mockk<UserDal> {
    every { insert(any()) } returnsArgument 0
}

如果您打算使用 Mockito ,则应删除 MockK 并使用假人kotlin :

If you intend to use Mockito, you should remove MockK and use mockito-kotlin:

val dal = mock<UserDal> {
    on { insert(any()) } doAnswer { it.arguments[0] }
}

这篇关于Kotlin Mockito始终返回作为参数传递的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆