我试图编写一个Android单元测试,测试是否在MainActivity中按下ImageButton会触发启动另一个活动的意图(Activity2)。这是我的代码:
public class MainActivityTest extends ActivityUnitTestCase<MainActivity> {
private Intent activityLaunchIntent;
public MainActivityTest(){
super(MainActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
activityLaunchIntent = new Intent(getInstrumentation().getTargetContext(), MainActivity.class);
}
public void testPreconditions() {
assertNotNull(activityLaunchIntent);
}
/**
* Tests that the button to launch Activity2 fires the correct Intent.
*/
@MediumTest
public void testLaunchButton_shouldLaunchActivity2() {
startActivity(activityLaunchIntent, null, null);
final ImageButton launchActivity2Button = (ImageButton) getActivity().findViewById(R.id.launchButton);
launchButton.performClick();
// Ensure that the intent to start the Activity2 has been launched
final Intent launchActivity2Intent = getStartedActivityIntent();
assertNotNull(launchActivity2Intent);
assertTrue(launchActivity2Intent.getClass().equals(SettingsActivity.class));
assertTrue(isFinishCalled());
}
}
当我尝试从AndroidStudio中运行单元测试时,我收到以下错误:
java.lang.RuntimeException: Method setUp in android.test.ActivityUnitTestCase not mocked. See http://g.co/androidstudio/not-mocked for details.
at android.test.ActivityUnitTestCase.setUp(ActivityUnitTestCase.java)
访问http://g.co/androidstudio/not-mocked后,我将以下内容添加到build.gradle文件中:
android {
// ...
testOptions {
unitTests.returnDefaultValues = true
}
}
但是,现在我收到以下错误:
java.lang.NullPointerException
at com.example.unittesting.MainActivityTest.setUp(MainActivityTest.java:24)
顺便提一下,MainActivityTest.java的第24行是:
activityLaunchIntent = new Intent(getInstrumentation().getTargetContext(), MainActivity.class);
有人可以告诉我这里发生了什么吗?这是一个简单的修复吗?或者我是以完全错误的方式做这件事。提前感谢您的帮助。