使用io.mockk 1.11.0
具有@JvmStatic函数的类
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
}
}
}测试是在从Log.e(...)返回null时验证调用了getDataJson()。
@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连接?
发布于 2022-05-28 22:36:15
mockkStatic的使用是正确的,但DataUtil不是静态的。
如果您的代码是kotlin,则必须使用object代替类:
对象DataUtil { ..。}对象LogUtil { ..}
PD:在@After方法中使用unmockkStatic,以避免可能影响其他测试的副作用。
https://stackoverflow.com/questions/71785361
复制相似问题