3

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.

4 Answers 4

3

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 } } 
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

This is actually a good idea. Just be careful, because nested tests can quickly get messy.
1

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.