Test-driven Android development
Running test cases on an Android emulator or on a real machine is slow. It usually takes a minute or more to build, deploy, and launch apps. This is not a TDD (test-driven development) mode. Robolectric provides a better way.
Maybe you've been trying to run test cases directly in the Java IDE using JUnit or testng, but you've been reporting java.lang.RuntimeException: Stub!
exceptions.
This exception is due to the absence of an Android runtime environment in the JDK. Now Robolectric, the Android Unit Test tool, simulates the jar package in the Android SDK to run test cases directly in the JVM, saving time. A robolectric test case is as follows:
// Test class for MyActivity @RunWith(RobolectricTestRunner.class) public class MyActivityTest { @Test public void clickingButton_shouldChangeResultsViewText() throws Exception { Activity activity = Robolectric.buildActivity(MyActivity.class).create().get(); Button pressMeButton = (Button) activity.findViewById(R.id.press_me_button); TextView results = (TextView) activity.findViewById(R.id.results_text_view); pressMeButton.performClick(); String resultsText = results.getText().toString(); assertThat(resultsText, equalTo("Testing Android Rocks!")); } }
Sdk,resource and native method simulation
Robolectric can handle display of controls, resource loading, and many other features on real machines that are implemented using native C. So we can use robolectric to simulate most of the operations on the real machine. We can easily obtain the source code of Robolectric, and directly view its simulation mechanism, so using robolectric, we can also simulate error conditions and some real sensor signals.
Execute test cases from the emulator
Robolectric allows us to use the JVM to execute test cases in project engineering or continuous integration (CI such as Hudson, Jenkins), eliminating the process of packaging, installing, and reducing the execution time of test cases from minutes to seconds.
No more mock frames needed
Using some mock frames, such as Mockito or Android mocks, you can simulate the Android operating environment to achieve the same effect as robolectric. This is an effective method, but the test case written in this way is, in many cases, the reverse implementation of the development code.
Robolectric's test style is more biased toward black-box testing, robolectric-style test cases are more focused on the performance of the app than the Android runtime, so the test cases written with robolectric are more effective. Of course this is also a look at the testers preferences, if you like can use both robolectric and mock frames.
Test-driven Android