Dav*_*ang 3 android unit-testing mockito kotlin
我开始学习Kotlin和Mockito,所以我编写了一个简单的模块来测试它.
AccountData_K.kt:
open class AccountData_K {
var isLogin: Boolean = false
var userName: String? = null
fun changeLogin() : Boolean {
return !isLogin
}
}
Run Code Online (Sandbox Code Playgroud)
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)
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,它会报告有关该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)
...
Run Code Online (Sandbox Code Playgroud)
我怀疑为什么这个方法不是模拟的方法调用...
所以请帮助我,谢谢.
默认情况下,Kotlin的课程和成员都是最终的.Mockito无法模拟最终类和方法.要使用Mockito,您需要使用open您想要模拟的方法:
open fun changeLogin() : Boolean {
return !isLogin
}
Run Code Online (Sandbox Code Playgroud)
进一步阅读
PS.在我看来,只要你通过ISP保持接口很小,使用Mockito或其他模拟框架的测试代码很少比手写假货/存根更易读和易懂.
| 归档时间: |
|
| 查看次数: |
2172 次 |
| 最近记录: |