using io.mockk 1.11.0
having some class with @JvmStatic
function
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()
.
@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
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?
The use of mockkStatic is correct, but DataUtil is not static.
If your code is kotlin, must use object instead class:
object DataUtil { .. } object LogUtil { .. }
PD: Use unmockkStatic in @After method for avoid side effects that may affect other test.