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 :

Saturday, April 20, 2013

Android - Robolectric - Unit testing start of an activity

Here is the android code to start an activity on click of a button

Android Code to test :

To test the above code,
1) First, You can call button's performClick to simulate a click event
2) Now, Get the shadowActivity using the robolectric's shadowOf method
3) This shadow Object has all the methods to test an activity
4) We can get the next started activity's Intent, using the getNextStartedActivity() method and assert it

Robolectric Test :

Monday, April 15, 2013

Android - Robolectric- Unit testing send SMS

Sending SMS in android is so simple, you just have to get the default SMSManager and call the sendTextMessage

Android Code :

Testing the above code is even simpler,
1) Get the shadowSMSManager
2) From it, we can get the lastSentTextMessageParams, which has the details abt the last sent SMS.
3) Assert with the expected values

Robolectric Test :

Sunday, April 14, 2013

Android - Robolectric - Unit testing setContentView

Normally the first thing we do in an Activity is to set the content view to a layout xml.
For example consider the below TestActivity, onCreate it sets its contentView to test_layout.xml

And the test_layout.xml is (Note : id of the root element android:id="@+id/test_layout_root")

In the robolectric test, we need to get the activity's content view id and assert it with the layout id