user739684 user739684 - 4 months ago 30
Android Question

Testing that button starts an Activity with Robolectric

Hi I have the following code:

@RunWith(Test9Runner.class)
public class MainActivityTest
{
private MainActivity activity;
private Button pressMeButton;

@Before
public void setUp() throws Exception
{
activity = new MainActivity();
activity.onCreate(null);
pressMeButton = (Button) activity.findViewById(R.id.button1);
}

@Test
public void shouldUpdateResultsWhenButtonIsClicked() throws Exception
{
pressMeButton.performClick();
ShadowActivity shadowActivity = shadowOf(activity);
Intent intent = shadowActivity.getResultIntent();
System.out.print(intent.toString());
}
}


But I have no idea how to test that pressing pressMeButton started a new Activity. Actually it does, but how to write the correct Robolectric unit test for this fact?

Answer

Use Robolectric's StartedMatcher

@RunWith(Test9Runner.class) 
public class MainActivityTest  {
    private MainActivity activity;
    private Button pressMeButton;

    @Before
    public void setUp() throws Exception 
    {
        activity = new MainActivity();
        activity.onCreate(null);
        pressMeButton = (Button) activity.findViewById(R.id.button1);
    }

    @Test
    public void shouldStartNextActivityWhenButtonIsClicked() 
    {
        pressMeButton.performClick();
        assertThat(activity, new StartedMatcher(NextActivity.class));
    }  
}
Comments