'How to link @BeforeEach method with specific @Test methods (Java, JUnit)?

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() {}

Is there a way to link the @BeforeEach method with @Test method, so the setup1() would run only before test1() and the setup2() would run only before test2()?



Solution 1:[1]

A distinct non-answer: don't do that!

The purpose of your unit tests is to help you to identify breakages in your production code quickly. Thus a base rule is: keep a very simple structure.

One aspect of a good unit test is: you look at the test method, and you know what is going on. If at all, you have to scroll to some setUp() method above (same file!) to see what is going on.

What you intend to do requires that future readers not only have to know about that base class, they also have to understand that there is some complex logic in play that uses different mechanisms per test method.

So, yes, avoiding code duplication is important for unit tests, too. But you avoid "getting there" by applying the same patterns that you use for your production code.

Solution 2:[2]

You can't really do this, but you can bundle Testcases with with @Nested classes.

public class Test {


    @BeforeEach
    void setUpForAll() {}

    @Nested
    class TestCasesWithPrecondition1{

        @BeforeEach
        void setUp1() {}
        
        @Test
        void test1() {}
    }

    @Nested
    class TestCasesWithPrecondition2{

        @BeforeEach
        void setUp2() {}

        @Test
        void test2() {}
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GhostCat
Solution 2