Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 216
bohdan Avatar asked May 25 '26 04:05

bohdan


2 Answers

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() {}
    }
}
like image 95
Herr Derb Avatar answered May 27 '26 23:05

Herr Derb


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.

like image 43
GhostCat Avatar answered May 27 '26 23:05

GhostCat