gpt4 book ai didi

android - 带有 mockito 测试的简单 kotlin 类导致 MissingMethodInvocationException

转载 作者:太空宇宙 更新时间:2023-11-03 11:36:40 24 4
gpt4 key购买 nike

我开始学习 Kotlin 和 Mockito,所以我编写了一个简单的模块来测试它。

AccountData_K.kt:

open class AccountData_K {
var isLogin: Boolean = false
var userName: String? = null

fun changeLogin() : Boolean {
return !isLogin
}
}

AccountDataMockTest_K.kt:

class AccountDataMockTest_K {
@Mock
val accountData = AccountData_K()

@Before
fun setupAccountData() {
MockitoAnnotations.initMocks(this)
}

@Test
fun testNotNull() {
assertNotNull(accountData)
}

@Test
fun testIsLogin() {
val result = accountData.changeLogin()
assertEquals(result, true)
}

@Test
fun testChangeLogin() {
`when`(accountData.changeLogin()).thenReturn(false)
val result = accountData.changeLogin()
assertEquals(result, false)
}
}

当我运行测试时,它报告有关 testChangeLogin() 方法的异常:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
3. the parent of the mocked class is not public.
It is a limitation of the mock engine.

at com.seal.materialdesignwithkotlin.AccountDataMockTest_K.testChangeLogin(AccountDataMockTest_K.kt:57)
...

我怀疑为什么这个方法不是对模拟的方法调用...

所以请帮助我,谢谢。

最佳答案

默认 Kotlin 的 classes and members are final . Mockito 无法 mock final classes nor methods .要使用 Mockito,您需要打开您希望模拟的方法:

open fun changeLogin() : Boolean {
return !isLogin
}

进一步阅读

附言。以我的拙见,只要通过即 ISP 保持接口(interface)较小即可。 ,使用 Mockito 或其他模拟框架的测试代码很少比手写的假货/ stub 更易读和更容易理解。

关于android - 带有 mockito 测试的简单 kotlin 类导致 MissingMethodInvocationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39365736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com