0

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.

Tuco
  • 902
  • 3
  • 18
  • 33

1 Answers1

1

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");
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
Zorawar Sachdev
  • 334
  • 1
  • 4
  • The thing about this is that I don't have a method for these fields like getSerial(), I just use Build.SERIAL. For example: `androidSystem.setSerialNumber(Build.SERIAL);` – Tuco Sep 21 '16 at 15:30
  • In that case, it is fairly simple to have a getter method for your androidSystem like `androidSystem.getSerialNumber(){ return serialNumber;}` and `androidSystem.setSerialNumber( String serialNumber ){ this.serialNumber=serialNumber; } ` Another example of getter/setter : http://stackoverflow.com/a/2036988/5097773 – Zorawar Sachdev Sep 21 '16 at 15:59
  • So in the end how did you solve mocking `android.os.Build.SERIAL` with Mockito? this answer doesnt really give any clue... – Guillaume Feb 05 '18 at 11:25