JUNIT空指针异常 [英] JUNIT Null Pointer Exception
问题描述
这是我第一次使用JUNIT,而我却无法使用它.
it's my first time using JUNIT and I literally cannot get it to work.
我有一个person类,其中有firstName和lastName,还有一个测试类,在其中需要测试方法.但是,每次我尝试测试一个方法时,如果我已经为特定方法编写了一个测试,它将失败.
I've got a person class, in which has firstName and lastName, and a test class in which I need to test the methods. Everytime I attempt to test one though, if i've wrote a test for the particular method, it fails.
这是我的代码.
人员班
public class Person {
private String firstName;
private String lastName;
public Person (String a, String b) {
firstName = a;
lastName = b;
}
public String getfirstName() {
return firstName;
}
public void setfirstName(String firstName) {
this.firstName = firstName;
}
public String getlastName() {
return lastName;
}
public void setlastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return firstName + " " + lastName;
}
}
人员测验班
public class PersonTest {
Person p1;
public PersonTest() {
Person p1 = new Person ("Thomas", "Brown");
}
@Before
public void setUp() {}
@After
public void tearDown() {}
@Test
public void testGetfirstName() {
assertEquals("Thomas", p1.getfirstName());
}
@Test
public void testSetfirstName() {}
@Test
public void testGetlastName() {
assertEquals("Brown", p1.getlastName());
}
@Test
public void testSetlastName() {}
@Test
public void testToString() {
assertEquals("Thomas Brown", p1.toString());
}
}
有人能指出我正确的方向吗?
Could anyone point me in the right direction?
推荐答案
这是正确的方法:
@Before
public void setUp() {
p1 = new Person ("Thomas", "Brown");
}
您的代码中有2个问题.
You have 2 problems in your code.
public PersonTest() {
Person p1 = new Person ("Thomas", "Brown");
}
这将创建一个局部变量,并且您的字段 p1
保持为 null
.
This creates a local variable and your field p1
stays null
.
第二个是在您的 setUp
方法中,您没有初始化 p1
.
The second is that in your setUp
method you do not initialize p1
.
用 @Before
注释的方法将在每次测试都应进行初始化之前运行.我还建议使用更具描述性的名称,因此您应该将 p1
更改为 target
或类似的名称.
The method you annotate with @Before
will run before every test to you should put the initialization there. I also suggest to use more descriptive names so you should change p1
to target
or something like that.
对于您的 set ...
方法,您可以执行以下操作:
For your set...
methods you can do something like this:
public class PersonTest {
private static final String TEST_FIRST_NAME = "some name";
Person target;
// ...
@Test
public void testSetFirstName() {
target.setFirstName(TEST_FIRST_NAME);
Assert.assertEquals(target.getFirstName(), TEST_FIRST_NAME);
}
}
此时,您可以假定 getFirstName
可以正常工作,因为您也对此进行了测试.
At that point you can assume that getFirstName
works since you have a test for it as well.
旁注:我认为,只要使用Eclipse生成getter和setter,就不必测试它们.只是不必要的.
A sidenote: I think you don't have to test getters and setters as long as you generate them with Eclipse. It is just unnesessary.
这篇关于JUNIT空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!