我想爲使用ActivityUnitTestCase的活動方法編寫單元測試。但是我總是在調用startActivity()
時收到空指針異常。以下是我的代碼。活動單元測試使用ActivityUnitTestCase
我調試,發現這總是返回null getInstrumentation().getTargetContext()
。但我真的不明白這裏發生了什麼。
CODE
public class ScoreBoardActivityTest extends ActivityUnitTestCase<ScoreBoardActivity> {
public ScoreBoardActivity activity;
public ScoreBoardActivityTest() {
super(ScoreBoardActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
startActivity(new Intent(getInstrumentation().getTargetContext(), ScoreBoardActivity.class), null, null);
activity = getActivity();
}
@Test
public void testActivityNotNull(){
Assert.assertNull(activity);
}
@Test
public void testBatsmanOneAddRunButtonClickUpdateTotalRuns(){
activity.onBatsmanOneAddRunClick(null);
Assert.assertEquals(activity.totalRuns, 1);
}
}
什麼,我做錯了什麼?
還有什麼我需要設置它?
變化'getInstrumentation()getTargetContext()''到getInstrumentation()getTargetContext()getApplicationContext();' – piotrek1543
如果不工作:。http://stackoverflow.com/questions/5544205/accessing-application-context -from-testsuite-in-setup-before-calling-getactivi – piotrek1543
@ piotrek1543感謝您的評論,但它不再工作.. – GoCrazy