Is there any way to annotate single test with hooks in JUnit5 like in Cucumber?
For example in cucumber it's possible to write hook like
@Before("@SomeTest")
public void beforeSomeTest(){
}
And then if we tag test with @SomeTest annotation then hook will run before test.
Is there any way to do this in JUnit5?
As mentioned by @johanneslink, extensions are the JUnit Jupiter way of doing stuff like that:
class MyTest {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@ExtendWith(MyExtension.class)
@interface MyAnnotation {
}
static class MyExtension implements BeforeTestExecutionCallback {
@Override
public void beforeTestExecution(ExtensionContext context) {
System.out.println("extension");
}
}
@Test
@MyAnnotation
void testWithExtension() {
System.out.println("test with extension");
}
@Test
void testWithoutExtension() {
System.out.println("test without extension");
}
}
Output:
extension
test with extension
test without extension