简体   繁体   中英

How to mock Build.VERSION.SDK_INT using mockk

How can I mock Build.VERSION.SDK_INT in mockk?

I've done the following:

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

I end up getting io.mockk.MockKException: Missing calls inside every { ... } block. once the code hits the every block.

You can build a wrapper around the Build config like this

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

Then mock the MyAppBuildConfig with mockkObject and return your desire version number

    mockkObject(MyAppBuildConfig)
    every { MyAppBuildConfig.getVersionSDKInt() } returns 22

I ended up modifying Build.VERSION.SDK_INT using reflection. I added the following helper:

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)
}

and then called it like this in my test:

setStaticFieldViaReflection(Build.VERSION::class.java.getField("SDK_INT"), 23)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM