Reference:
Robolectric Homepage
http://robolectric.org/getting-started/
A good Tutorial of Setting up Robolectric
https://github.com/codepath/android_guides/wiki/Robolectric-Installation-for-Unit-Testing
1. modify the Top-level build.gradle.
Add robolectric gradle plugin to dependencies.
dependencies {
...
classpath 'org.robolectric:robolectric-gradle-plugin:1.0.1'
}
2. modify the app-level build.gradle.
Add following line
apply plugin: 'org.robolectric'
...
dependencies {
...
testCompile 'junit:junit:4.12'
testCompile 'org.robolectric:robolectric:2.4'
}
3. Add test file under [Your Project]/app/src/test/[test files]
The test folder is at the same level with the "main" folder.
4. Write the test files
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
@Config(emulateSdk = 18)
@RunWith(RobolectricTestRunner.class)
public class TestFile {
@Test
public void testIt() {
// failing test gives much better feedback
// to show that all works correctly ;)
assertEquals(false, true);
}
}
5. run the test command "./gradlew test" to run test