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 :
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
public void onButtonClick(View v) {
startActivity(new Intent(this, SecondActivity.class));
}
}

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 :
@RunWith(RobolectricTestRunner.class)
public class MainActivityTest {
private MainActivity mainActivity;
private Button button;
@Before
public void setUp() {
mainActivity = new MainActivity();
mainActivity.onCreate(null);
button = (Button) mainActivity.findViewById(R.id.open_button);
}
@Test
public void shouldStartTheSecondActivityOnButtonClick() throws Exception {
ShadowActivity shadowActivity = shadowOf(mainActivity);
button.performClick();
Intent startedIntent = shadowActivity.getNextStartedActivity();
assertThat(startedIntent.getComponent().getClassName(),
equalTo(SecondActivity.class.getName()));
}
}

No comments:

Post a Comment