[英]mockk, get error when using mockkstatic for stub static function
using io.mockk 1.11.0使用 io.mockk 1.11.0
having some class with @JvmStatic
function有一些带有
@JvmStatic
函数的类
class LogUtil {
@JvmStatic
fun logData(jsonStr: String) {
val jsonObj = getDataJson(jsonStr)
if (jsonObj == null) {
Log.e("+++", "+++ wrong json")
}
// ......
}
}
data util数据工具
class DataUtil {
@JvmStatic
fun getDataJson(json: String): JSONObject? {
return try {
JSONObject(json)
} catch (e: Exception) {
null
}
}
}
The test is to verify the Log.e(...)
is called when a null is returned from getDataJson()
.测试是验证当从
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()) }
}
got error出错了
io.mockk.MockKException: Failed matching mocking signature for
left matchers: [any()]
if change to every { DataUtil.getDataJson("test string") } returns null
, it will get error如果更改为
every { DataUtil.getDataJson("test string") } returns null
,则会出错
MockKException: Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock
How to use mockkStatic
for a @JvmStatic
unction?如何将
mockkStatic
用于@JvmStatic
函数?
The use of mockkStatic is correct, but DataUtil is not static. mockkStatic 的使用是正确的,但是 DataUtil 不是静态的。
If your code is kotlin, must use object instead class:如果您的代码是 kotlin,则必须使用对象而不是类:
object DataUtil { .. } object LogUtil { .. }对象 DataUtil { .. } 对象 LogUtil { .. }
PD: Use unmockkStatic in @After method for avoid side effects that may affect other test. PD:在 @After 方法中使用 unmockkStatic 以避免可能影响其他测试的副作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.