Home > Blockchain >  How to reuse objects in JUnit testing?
How to reuse objects in JUnit testing?

Time:11-08

I don't want to create the same objects for every unit test but I can't figure out how to reuse objects for multiple testing methods.

I know about @BeforeAll and I am trying to use it to initialize a set of static objects that I can reuse in multiple unit tests.

Somehow I can't get it to work.

For example, I could have a class called Date with the initializer Date(int day, int month, int year) and I am trying to test its equals(Date other) method. I now want to create Date objects that I can also use for other test methods. This is what I am trying:

public class MyTests {
   
    static Date d1, d2, d3;

    @BeforeAll
    public void setup() {
        d1 = new Date(7, 11, 2021);
        d2 = new Date(7, 11, 2021);
        d3 = new Date(1, 11, 1990);
    }

    @Test
    public void TestDateEquals() {
        Assert.assertTrue(d1.equals(d2));
        Assert.assertFalse(d2.equals(d3));
    }
}

This throws a NullPointerException. How can I make it work?

Thank you!

CodePudding user response:

what junit version are you using ? BeforeAll works for junit5(org.junit.jupiter.api.BeforeAll) and assert is org.junit.jupiter.api.Assertions.assertTrue

i ran you code with junit5 and it worked after add static to setup method. You also can follow @Turing85 suggestion to initialize the objects

CodePudding user response:

Any methods annotated by @Before... or @After... should be static to work properly. Just mark your setup() method static and run. That's a requirement of JUnit current implementation.

  • Related