bohdan
bohdan

Reputation: 445

How can I link @BeforeEach with @Test method using JUnit extensions?

For example, we have 2 classes: BaseTest and Test; Test extends BaseTest.

BaseTest.class contains 2 methods with @BeforeEach annotations.

@BeforeEach
  void setUp1() {}

@BeforeEach
  void setUp2() {}

Test.class contains 2 methods with @Test annotations.

@Test
void test1() {}

@Test
void test2() {}

I want to link the @BeforeEach method with @Test method, so the setup1() would run only before test1() and the setup2() - only before test2().

I would appreciate a code sample of this task completed using JUnit extensions.

Upvotes: 3

Views: 680

Answers (4)

Raedwald
Raedwald

Reputation: 48624

You don't need to put test set up code only in @BeforeEach annotated methods. You can put it in the @Test method or (perhaps better) in a method called from the @Test method.

Upvotes: 0

Mureinik
Mureinik

Reputation: 311028

The operative word in @BeforeEach is each. These methods run before each test, and aren't really suitable for the usecase you're describing. If you need such a tight coupling, I'd suggest to move away from JUnit annotations, and just call the setup methods directly:

public class BaseTest {
    void setUp1() {}

    void setUp2() {}
}

public class Test extends BaseTest {
    @Test
    void test1() {
        setUp1();
        // test logic
    }

    @Test
    void test2() {
        setUp2();
        // test logic
    }
}

Upvotes: 3

Youssef NAIT
Youssef NAIT

Reputation: 1530

In Junit 5 you have a new feature called Nested tests that allows you to have nested classes each with it's own BeforeAll and AfterAll. This requires a little bit of change to your classes hierarchy BaseTest.class and Test.class but works like a charm :

@Nested Denotes that the annotated class is a non-static nested test class. @BeforeAll and @AfterAll methods cannot be used directly in a @Nested test class unless the "per-class" test instance lifecycle is used. Such annotations are not inherited.

Upvotes: 2

EricSchaefer
EricSchaefer

Reputation: 26330

This is not possible like this. There are some other options you could consider:

  • Put setup2() and test2() in another test class. Since test1 and test2 do not share the setup ("fixture") they should be in separate classes anyway.
  • Remove the @BeforeEach annotation and call the setup methods explicitly at the start of the actual test methods.

Upvotes: 1

Related Questions