performclick()期间出现NullPointerException

时间:2013-11-15 16:36:39

标签: java android nullpointerexception

我正在对活动进行单元测试。我的活动有一个调用简单方法的按钮(没有活动,服务或其他任何东西)。

  

java.lang.NullPointerException at   com.android.my.test.MyActivityTest.testPerformClick(MyActivity.java:41)at at   java.lang.reflect.Method.invokeNative(Native Method)at   android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:205)   在   android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:195)   在   android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:175)   在android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)   在android.test.AndroidTestRunner.runTest(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();
    }
}

1 个答案:

答案 0 :(得分:1)

我的猜测是你需要将MyActivity更改为此。您的测试为方法getButton()

获取NULL
public class MyActivity extends Activity implements OnClickListener 
{
    private Button b;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        b=new Button();
        b.setOnClickListener(this);
    }

    @Override
    public void onClick(View arg0) 
    {
        method();
    }

    private void method()
    {
        ...
    }

    public Button getButton()
    {
        return b;
    }
}