java在安卓中测试类编辑文本字段时出现空指针异常
这是我想测试EditText的类。但是当我尝试在测试clas中分配EditText字段时,它显示了一个空指针异常。对于这个问题,我省略了其他无需使用的代码
public class LogInActivity extends ActionBarActivity {
private Button signUpButton;
private Button logInButton;
private Intent signUpChoiceIntent;
private Intent homeActivityIntent;
private String username;
private String password;
private EditText usernameTextField;
private EditText passwordTextField;
private HumLogController humLogController;
private String error;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
humLogController = (HumLogController) getIntent().getSerializableExtra("controllerObject");
setIntentAndButton();
}
private void setAndCheckFields(){
/** I want to test this, (view with id:- logInUsernameField ) which is working fine in practice, but not passing the test. When I try to call the same id in Test class with instance of this class, it gives a null pointer exception. */
usernameTextField = (EditText) findViewById(R.id.logInUsernameField);
}
这是我正在测试EditText字段的测试类,但给出了一个空指针异常
public class LogInActivityInstrumentTest extends InstrumentationTestCase{
LogInActivity logInActivity;
@Override
protected void setUp() throws Exception{
super.setUp();
logInActivity = new LogInActivity();
}
public void testUsernameTextViewNullTest(){
// The line below is line 23. Which is giving null pointer Exception...?
EditText text = (EditText) logInActivity.findViewById(R.id.logInUsernameField);
assertNotNull(text);
}
@Override
protected void tearDown() throws Exception{
super.tearDown();
}
}
日志cat如下所示
java.lang.NullPointerException
at 安卓.app.Activity.findViewById(Activity.java:1853)
at com.example.praduman.humlog.tests.LogInActivityInstrumentTest.testUsernameTextViewNullTest(LogInActivityInstrumentTest.java:23)
at java.lang.reflect.Method.invokeNative(Native Method)
at 安卓.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at 安卓.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
at 安卓.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at 安卓.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at 安卓.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at 安卓.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1701)
# 1 楼答案
不能像创建活动那样简单地调用其构造函数。在测试环境中,您需要某种工具来允许一切正常工作。试着看看Espresso(用于设备内测试)甚至Robolectric(用于JVM测试)
# 2 楼答案
您不能像上面代码中那样使用构造函数创建活动的实例
尝试在^{中更改以下内容
运行测试的文档可以在开发者的here上找到。安卓com
在您发布的代码中,简单地使用其构造函数创建Activty并不会在activity预期的生命周期中运行它。之所以使用
NullPointerException
,是因为onCreate
尚未运行,这意味着在调用setContentView()
之前,您正试图查找一个视图,因此,该视图实际上是空的