Android Code to test :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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