Android Unit Testing - 测试返回null的方法

时间:2017-10-19 05:35:12

标签: java android unit-testing junit mockito

测试方法:

public static String getDeviceName() {
    String manufacturer = Build.MANUFACTURER;
    String model = Build.MODEL;
    if (model.startsWith(manufacturer)) {
        return WordUtils.capitalize(model);
    } else {
        return WordUtils.capitalize(manufacturer) + " " + model;
    }
}

测试用例:

@Test
public void testGetDeviceName() throws Exception {
    String deviceNameTest = "device name";
    assertEquals(deviceNameTest, DeviceUtil.getDeviceName());
}

错误

  

显示java.lang.NullPointerException

     

getDeviceName(DeviceUtil.java:15)   DeviceUtilTest.testGetDeviceName(DeviceUtilTest.java:18)

     

DeviceUtil.getDeviceName() - >返回null

2 个答案:

答案 0 :(得分:2)

您无法测试getDeviceName()Build.MANUFACTURERBuild. MODEL将返回null。制造商和型号也来自设备,您的IDE如何获得它?

BTW如果你想用静态方法测试Util类,我建议你使用  PowerMock或者你必须创建用于测试的包装器类。

答案 1 :(得分:0)

您可以使用以下代码在测试中设置 android.os.Build.MANUFACTURER 和 android.os.Build.MODEL 的值:

ReflectionHelpers.setStaticField(android.os.Build::class.java, "MANUFACTURER", "My Manufacturer")
ReflectionHelpers.setStaticField(android.os.Build::class.java, "MODEL", "My Model ")

在下面找到完整的代码。

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
internal class DeviceInfoManagerImplTest{
    private lateinit var manager: DeviceInfoManagerImpl
    private lateinit var context: Context
    private lateinit var firebaseTokenManager: FirebaseManager
    private lateinit var dispatchers: CoroutineDispatchers

    @BeforeAll
    fun setUp(){
        context = mockk(relaxed = true)
        firebaseTokenManager= mockk()
        dispatchers = spyk()
        manager = DeviceInfoManagerImpl(context,
                firebaseTokenManager,
                dispatchers)

        coEvery { dispatchers.io } returns
                CoroutineDispatchersImpl().io

        coEvery { firebaseTokenManager.getToken() } returns "token"
        ReflectionHelpers.setStaticField(android.os.Build::class.java, "MANUFACTURER", "My Manufacturer")
        ReflectionHelpers.setStaticField(android.os.Build::class.java, "MODEL", "My Model ")

        mockkStatic(Settings.Secure::class)

        every {
            Settings.Secure.getString(context.contentResolver,
                    Settings.Secure.ANDROID_ID)
        } answers {
            "My ID"
        }
    }

    @Test
    fun test(){
        val deviceInfo = runBlocking { manager.getDeviceInfo() }
        println(deviceInfo.deviceManufacturer)
        println(deviceInfo.deviceUniqueIdentification)
    }
}