Wednesday, April 24, 2013

Android - Robolectric - Unit testing request location updates (LocationManager)

Here is the android code to register for network, GPS and passive location updates on activity create

Android Code to test :

To test the above code,
1) First you need to create a mock location
2) Get the ShadowLocationManager using the robolectric's shadowOf method
3) This shadow Object has a method called 'simulateLocation' to mock a location update.
4) Now we can assert the actual value obtained by the listener with the expected value

Robolectric Test :

2 comments:

  1. Useful stuff, only I had trouble calling the onCreate the way you do. This is another way:

    mainActivity = Robolectric.buildActivity(MainActivity.class).create().get();

    ReplyDelete