我正在做一個活動的單元測試。我的活動有一個按鈕,調用一個簡單的方法(沒有活動,服務或其他任何東西)。NullPointerException在performclick()
在 機器人處 java.lang.reflect.Method.invokeNative(本機方法) com.android.my.test.MyActivityTest.testPerformClick(MyActivity.java:41)顯示java.lang.NullPointerException。 test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:205) 在 android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:195) 在 android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:175) 在機器人。 test.AndroidTestRunner.runTest(AndroidTestRunner.java:169) at android.test.AndroidTestRunner.r unTest(AndroidTestRunner.java:154) 在 android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430) 在 android.app.Instrumentation $ InstrumentationThread.run(Instrumentation.java:1447)
我的測試是這樣的:
public class MyActivityTest extends ActivityInstrumentationTestCase2<MyActivity> {
MyActivity a;
public MyActivityTest() {
super("com.android.my", MyActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
a = this.getActivity();
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
public void testPerformClick() {
a.getButton().performClick();
}
}
而我的活動是這樣的。
public class MyActivity extends Activity implements OnClickListener {
private Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
button = new Button();
button.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
method();
}
private void method() {
// [...]
}
public void getButton() {
return button();
}
}
'a'或'a.getButton()'爲'null'。 –
a.getButton返回null,但是它應該返回活動按鈕嗎? –
如果您可以發佈可編譯代碼,這很有用。 –