运行 JUnit 5 中标记测试的特定设置

Running specific set-up for tagged tests in JUnit 5

我使用 JUnit 5 和 Java 来编写集成测试。其中一些连接到数据库,我正在寻找一种方法:

用于使用特定注释进行注释的测试。

到目前为止,我发现使用标签可以执行以下操作:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.Tag;

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Tag("database")
public @interface Database {}

然后使用@Database注解filter annotated tests out

现在我正在寻找一种解决方案来为所有使用此注释进行注释的测试连接测试设置。可能是什么?

解决方案需要两个步骤:

  • 编写一个 Jupiter 扩展,例如MyDatabaseSetup 完成必要的 setup/teardown 工作
  • @ExtendWith(MyDatabaseSetup.class) 添加到您的数据库注释

现在每个 class 或使用 @Database 注释的测试方法也将使用扩展名。