kotlin测试mockito报错ArgumentMatchers.any must not be null
项目使用springboot+kotlin进行开发,项目代码如下:IAccountService
:
interface IAccountService : IService<AccountInfo> {
fun simpleInfo(id: Long): AccountInfo?
fun register(accountInfo: AccountInfo): Boolean
}
AccountServiceImpl
:
@Service
class AccountServiceImpl : IAccountService, ServiceImpl<AccountMapper, AccountInfo>() {
override fun simpleInfo(id: Long): AccountInfo? {
val simpleInfo = baseMapper.simpleInfo(id);
return simpleInfo
}
override fun register(accountInfo: AccountInfo): Boolean {
return baseMapper.insert(accountInfo) > 0
}
}
AccountInfo
:
data class AccountInfo (
var uid: Long? = null,
// 用户名
var username: String? = null,
// 用户昵称
var nickname: String? = null,
) {
}
测试代码如下:
@RunWith(SpringRunner::class)
@SpringBootTest
@AutoConfigureMockMvc
class AccountControllerTest {
@Autowired
lateinit var mockMvc: MockMvc
@MockBean
private lateinit var accountService: IAccountService
@Test
fun register() {
`when`(accountService.simpleInfo(anyLong())).thenReturn(AccountInfo(100))
val simpleInfo = accountService.simpleInfo(1L)
`when`(accountService.register(any(AccountInfo::class.java))).thenReturn(true)
accountService.register(AccountInfo(100))
}
}
运行上边的测试,simpleInfo
方法可以正常执行,但是当执行 register
测试方法的第三行的when
时,报以下错误:
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为
any(AccountInfo::class.java)
可能返回空,但是我的方法是非空的参数,所以无法匹配,找了好久终于找到了解决办法:自定义
MockitoHelper
类使用
MockitoHelper.anyObject()
来代替Mockito.any()
方法导入
import com.nhaarman.mockitokotlin2.any
,使用这里的any()
方法我这里采用第二种方法,引入新的类库,最后的测试方法如下:
问题解决。
参考: