简体   繁体   中英

JUnit test on setters and getters failing

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.

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.
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM