Tuco Tuco - 2 months ago 15
Java Question

Writing tests for Android app that uses some fields from android.os.Build

I'm currently trying to write some tests for an Android app I have with no UI (simple background service). My Android service basically calls another class that takes care of most of the work. It is this class that I want to test, but in it I use stuff like:


  • Build.SERIAL

  • Build.VERSION.RELEASE

  • BatteryManager.BATTERY_HEALTH_COLD

  • etc



to create a JSON object.

These values are null in my tests as I'm trying to test without relying on an Android device. Is there a way to mock these values or change their default values during the tests? What my tests really want to verify is that the JSON object I'm building using these values is built correctly.

Answer

Is there a way to mock these values or change their default values during the tests?

For Android we use a library called Mockito

A simple way to do what you want would be:

    //  create mock
    YourBackgroundService test = Mockito.mock(YourBackgroundService.class);

    // define return value for method getSerial()
    when(test.getSerial()).thenReturn("42UNIV");

    // use mock in test....
    assertEquals(test.getSerial(), "42UNIV");