Search code examples
javajunit

JUnit setUp doesn't create object


Why do I get a NullPointerExeption for testManuscript when trying to run my test?

This is my Manuscript.java:

package org.lhoffjann;


public class Manuscript {
private String msID;
private String path;
    public void setMSid(String msID){
        this.msID = msID;
    }

    public String getMSid() {
        return this.msID;
    }
}

This is my ManuscriptTest.java:

package org.lhoffjann;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class ManuscriptTest {
    private static Manuscript testManuscript;

    @Before
    public void setUp(){
        testManuscript = new Manuscript();
    }
    @Test
    public void testGetMSid() {
        testManuscript.setMSid("1234");
        assertTrue("1234" == testManuscript.getMSid());
    }
}

Solution

  • You have imported @Test from JUnit 5, while you're using @Before from JUnit 4, that combination doesn't work. You need to choose which JUnit version you want to use, 4 or 5, and then consistently import classes from that JUnit version. I would recommend using JUnit 5, and removing all JUnit 4 dependencies from your classpath, or at least configure your IDE to not suggest those imports.

    For this specific case, replace @Before (org.junit.Before) with @BeforeEach (org.junit.jupiter.api.BeforeEach).

    In the example as shown, you don't even need this setUp method, as each test-execution gets its own instance of the test class. You can use:

    private Manuscript testManuscript = new Manuscript();
    

    That is, remove static, initialize the field directly, and remove the setUp method.

    Even if you continue to use the setUp method, I recommend removing the static, so testManuscript is an instance field, like it is actually used.