Reputation: 8030
i'm getting a nullpointerexception when i run the junit test in eclipse. what am i missing here?
MainTest
public class MainTest {
private Main main;
@Test
public void testMain() {
final Main main = new Main();
main.setStudent("James");
}
@Test
public void testGetStudent() {
assertEquals("Test getStudent ", "student", main.getStudent());
}
@Test
public void testSetStudent() {
main.setStudent("newStudent");
assertEquals("Test setStudent", "newStudent", main.getStudent());
}
}
setters and getters are in the Main class
Main
public String getStudent() {
return student;
}
public void setStudent(final String studentIn) {
this.student = studentIn;
}
thanks.
Upvotes: 0
Views: 1220
Reputation: 79838
Every test method gets a new instance of MainTest
. This means that the changes you make in your first method won't show up in your second method, and so on. There is no sequential relationship between one test method and another.
You need to make each method a self-contained test that tests one aspect of your class's behaviour.
Upvotes: 4
Reputation: 9038
You need to initialize your main object before using it
You can do it either on an @Before
method or inside the test itself
.
OPTION 1
Change
@Test
public void testSetStudent() {
main.setStudent("newStudent");
assertEquals("Test setStudent", "newStudent", main.getStudent());
}
to
@Test
public void testSetStudent() {
main = new Main();
main.setStudent("newStudent");
assertEquals("Test setStudent", "newStudent", main.getStudent());
}
OPTION 2
Create a @Before method, when using @Before the main field will be created before any @Test is executed, there is another option, option 3, to use @BeforeClass
@Before
public void before(){
main = new Main();
}
OPTION 3
@BeforeClass
public static void beforeClass(){
//Here is not useful to create the main field, here is the moment to initialize
//another kind of resources.
}
Upvotes: 4