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
You can not test getDeviceName()
, Build.MANUFACTURER
and Build. MODEL
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.
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)
}
}
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.