gpt4 book ai didi

java - Performclick() 期间出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 13:50:25 28 4
gpt4 key购买 nike

我正在对一项 Activity 进行单元测试。我的 Activity 有一个调用简单方法的按钮(没有 Activity 、服务或其他任何内容)。

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

}

我的 Activity 是这样的。

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();
}
}

最佳答案

我的猜测是您需要将 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;
}
}

关于java - Performclick() 期间出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20005988/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com