1. Robolectric
Robolectric允许我们可以在JVM上对Android应用程序进行测试
Robolectric框架允许我们编写单元测试,测试的代码使用了Android API,在本地JVM上运行
Robolectric mock了android.jar文件中的部分Android framework的代码
Robolectric支持资源的处理,例如inflation of views
Robolectric将所有Android类替换为shadow对象。
2. 使用Robolectric
3. Roboelectric test example
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class MyActivityTest {
private MainActivity activity;
@Before
public void setup() {
activity = Robolectric.buildActivity(MainActivity.class) .create().get();
}
@Test
public void shouldHaveHappySmiles() throws Exception {
String hello = new MainActivity().getResources().getString( R.string.hello_world);
assertThat(hello, equalTo("Hello world!"));
}
@Test
public void checkActivityNotNull() throws Exception {
assertNotNull(activity);
}
@Test
public void buttonClickShouldStartNewActivity() throws Exception {
Button button = (Button) activity.findViewById( R.id.button2 );
button.performClick();
Intent intent = Shadows.shadowOf(activity).peekNextStartedActivity();
assertEquals(SecondActivity.class.getCanonicalName(), intent.getComponent().getClassName());
}
@Test
public void testButtonClick() throws Exception {
MainActivity activity = Robolectric.buildActivity(MainActivity.class) .create().get();
Button view = (Button) activity.findViewById(R.id.button1);
assertNotNull(view);
view.performClick();
assertThat(ShadowToast.getTextOfLatestToast(), equalTo("Lala") );
}
}