Construction of the robolectric environment and robolectric
Recently I have been studying Test-Driven Development. Test-Driven Development is a method of extreme programming, we recommend that you write the test code as needed before writing the code (of course, this test code cannot be passed), and then write the formal code based on the test code, the code must pass the test code step by step. If we can also use test-driven development in Android development, it will greatly speed up our development. However, we all know that unit testing for Android is really a headache. running on a real machine or simulator that every test requires will greatly slow down our testing speed.
Robolectric is a unit test framework for Android. It is fascinating that it allows your Android code to run on jvm (not an Android virtual machine, this means that you do not need to install your apk on the machine during unit testing, which will greatly reduce our testing time. (Wouldn't it be nice to run your Android tests directly from inside your IDE ?)
Official robolectric website
I encountered a lot of difficulties during the construction of robolectric and compared the online solutions, so I had to explore it myself. Today I will record the construction of the robolectric environment.
1. Development Environment android-studio
2. jar packages,
3. After importing the jar package, you need to modify the configuration of the project: There is a build variants in the lower left corner of Android studio. Click it and change test artifact to Unit tests.
4. Compile the test code:
@ RunWith (RobolectricGradleTestRunner. class) @ Config (constants = BuildConfig. class) public class MyTest {@ Test public void testTest () {MainActivity mainActivity = Robolectric. setupActivity (MainActivity. class); TextView textView = (TextView) mainActivity. findViewById (R. id. text); assertEquals (textView. getText (), "Hello World! 1 ");}}View Code
Note the annotation above the test class
5. Run this unit test method. Some items may be downloaded during the first run. After the unit test is downloaded, It will be executed in the same way as junit.