Last active
June 19, 2019 12:29
-
-
Save swissonid/27a113efb633a03b242cfedb49dcd506 to your computer and use it in GitHub Desktop.
Set SDK version of android in a UnitTest. Using some reflection magice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Test | |
fun `someTest-which-should-test-diffrent-behavior-on-diffrent-sdk-version`() { | |
setSDK(Build.VERSION_CODES.N) | |
//some test | |
setSDK(Build.VERSION_CODES.M) | |
// some test again with diffrent SDK verion | |
} | |
fun setSDK(sdkVersion: Int) { | |
setFinalStatic(Build.VERSION::class.java.getField("SDK_INT"), sdkVersion) | |
} | |
@Throws(Exception::class) | |
fun setFinalStatic(field: Field, newValue: Any) { | |
field.isAccessible = true | |
val modifiersField = Field::class.java.getDeclaredField("modifiers") | |
modifiersField.isAccessible = true | |
modifiersField.setInt(field, field.modifiers and Modifier.FINAL.inv()) | |
field.set(null, newValue) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment