Home > Mobile >  junit5 - is @BeforeAll necessary to instantiate objects?
junit5 - is @BeforeAll necessary to instantiate objects?

Time:07-14

Is there a difference between creating an instance variable and creating a member variable in a method marked with a @BeforeAll annotation?

Public class Example1Test{

Lift testClass = null;

@BeforeAll
public void init() {
    testClass = new Lift();
}

@Test
...
}

VS

Public class Example2Test{
Lift testClass = new testClass;

@Test
...
}

CodePudding user response:

@BoforeAll is used to make sure that the annotated method should be executed before all the @ParameterizedTest,@Test, @RepeatedTest and @TestFactory methods in the current class. so if you want this method to be run before any other method then yes you have to annotate this.

CodePudding user response:

If object, that is defined and initialized at the same time (like Lift class in your code snippet), has state, it's better to initialize it in @BeforeEach. Object's context is cleared before every test. This makes your test independent from each other.

  • Related