Stub value of Build.VERSION.SDK_INT in Local Unit Test

白昼怎懂夜的黑 提交于 2019-12-03 09:41:21

问题


I am wondering if there is anyway to stub the value of Build.Version.SDK_INT? Suppose I have the following lines in the ClassUnderTest:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    //do work
}else{
    //do another work
}

How can I cover all the code ?

I mean I want to run two tests with different SDK_INT to enter both blocks.

Is it possible in android local unit tests using Mockito/PowerMockito?

Thanks


回答1:


Change the value using reflection.

 static void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

    field.set(null, newValue);
 }

And then

 setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 123);

It is tested. Works.




回答2:


As an alternative to reflection, you can use your own class that checks for API and then use Mockito to test the API-Dependent logic in fast JVM unit tests.

Example class

import android.os.Build

class SdkChecker {

    fun deviceIsOreoOrAbove(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O

}

Example tested method

fun createNotificationChannel(notificationManager: NotificationManager) {
    if (sdkChecker.deviceIsOreoOrAbove()) { // This sdkChecker will be mocked
        // If you target Android 8.0 (API level 26) you need a channel
        notificationManager.createNotificationChannel()
    }
}

Example unit tests

import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import com.nhaarman.mockito_kotlin.whenever

@Test
fun createNotificationChannelOnOreoOrAbove() {
    whenever(mockSdkChecker.deviceIsOreoOrAbove()).thenReturn(true)

    testedClass.createNotificationChannel(mockNotificationManager)

    verify(mockNotificationManager).createNotificationChannel()
}

@Test
fun createNotificationChannelBelowOreo() {
    whenever(mockSdkChecker.deviceIsOreoOrAbove()).thenReturn(false)

    testedClass.createNotificationChannel(mockNotificationManager)

    verifyZeroInteractions(mockNotificationManager)
}


来源:https://stackoverflow.com/questions/38074224/stub-value-of-build-version-sdk-int-in-local-unit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!