问题
it's my first time using JUNIT and I literally cannot get it to work.
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.
Here is my code.
Person Class
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;
}
}
Person Test class
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?
回答1:
This is the right way to do it:
@Before
public void setUp() {
p1 = new Person ("Thomas", "Brown");
}
You have 2 problems in your code.
public PersonTest() {
Person p1 = new Person ("Thomas", "Brown");
}
This creates a local variable and your field p1
stays null
.
The second is that in your setUp
method you do not initialize p1
.
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.
Edit: 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);
}
}
At that point you can assume that getFirstName
works since you have a test for it as well.
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.
回答2:
Change
Person p1 = new Person ("Thomas", "Brown"); //this is local variable
to
p1 = new Person ("Thomas", "Brown");// and this will use the instance variable
来源:https://stackoverflow.com/questions/19978692/junit-null-pointer-exception