使用io.mockk 1.11.0
与CCD_ 1函数有某种类
class LogUtil {
@JvmStatic
fun logData(jsonStr: String) {
val jsonObj = getDataJson(jsonStr)
if (jsonObj == null) {
Log.e("+++", "+++ wrong json")
}
// ......
}
}
数据实用程序
class DataUtil {
@JvmStatic
fun getDataJson(json: String): JSONObject? {
return try {
JSONObject(json)
} catch (e: Exception) {
null
}
}
}
测试的目的是验证当getDataJson()
返回null时是否调用了Log.e(...)
。
@Test
fun test_() {
io.mockk.mockkStatic(android.utils.Log::class)
io.mockk.mockkStatic(DataUtil::class)
every { DataUtil.getDataJson(any()) } returns null //<== error points to this line
LogUtil.logData("{key: value}")
verify(exactly = 1) { android.utils.Log.e("+++", any()) }
}
得到错误
io.mockk.MockKException: Failed matching mocking signature for
left matchers: [any()]
如果更改为every { DataUtil.getDataJson("test string") } returns null
,则会出现错误
MockKException: Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock
如何将mockkStatic
用于@JvmStatic
函数?
mockStatic的使用是正确的,但DataUtil不是静态的。
如果您的代码是kotlin,则必须使用对象而不是类:
对象DataUtil{..}对象LogUtil{..}
PD:在@After方法中使用unlockkStatic,以避免可能影响其他测试的副作用。