2

Method to test:

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 case:

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

Error

java.lang.NullPointerException

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

DeviceUtil.getDeviceName() -> returns null

Komal12
  • 3,340
  • 4
  • 16
  • 25
Renz Manacmol
  • 869
  • 12
  • 27

2 Answers2

2

You can not test getDeviceName(), Build.MANUFACTURER and Build. MODEL will return null. Also manufacturer and model are from device, how your IDE can get it?

BTW if you want to test Util class with static method, i suggest you to use PowerMock as well or you have to create wrapper class of util for testing.

kimkevin
  • 2,202
  • 1
  • 26
  • 48
0

You can just set the value of the android.os.Build.MANUFACTURER and android.os.Build.MODEL in your test with thee following code:

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

Find below the full piece of code.

@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)
    }
}
Hoshouns
  • 2,420
  • 23
  • 24