12

如何在 mockk 中模拟 Build.VERSION.SDK_INT?

我做了以下事情:

@Test
fun testFoo(){
    mockkStatic(Build::class)
    mockkStatic(Build.VERSION::class)
    every {
        Build.VERSION.SDK_INT
    } answers { 22 }
}

io.mockk.MockKException: Missing calls inside every { ... } block.一旦代码遇到问题,我最终会得到every

4

2 回答 2

6

您可以像这样围绕构建配置构建一个包装器

object MyAppBuildConfig {
    fun getVersionSDKInt(): Int {
        return Build.VERSION.SDK_INT
    }
}

然后用 mockkObject 模拟 MyAppBuildConfig 并返回你想要的版本号

    mockkObject(MyAppBuildConfig)
    every { MyAppBuildConfig.getVersionSDKInt() } returns 22
于 2019-02-10T07:56:54.863 回答
1

我最终Build.VERSION.SDK_INT使用反射进行了修改。我添加了以下助手:

private fun setStaticFieldViaReflection(field: Field, value: Any) {
  field.isAccessible = true
  Field::class.java.getDeclaredField("modifiers").apply {
    isAccessible = true
    setInt(field, field.modifiers and Modifier.FINAL.inv())
  }
  field.set(null, value)
}

然后在我的测试中这样称呼它:

setStaticFieldViaReflection(Build.VERSION::class.java.getField("SDK_INT"), 23)
于 2022-01-07T11:32:08.153 回答