Reputation: 445
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
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
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
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
Reputation: 26330
This is not possible like this. There are some other options you could consider:
Upvotes: 1