如何在运行nativeTest时排除不支持原生测试的Spring Boot测试类?
在Maven的nativeTest Profile中排除特定测试类
完全可以实现,下面是两种常用的解决方案,既能让标注的测试在JVM模式下正常执行,又能在nativeTest Profile中跳过它们:
方案一:利用测试标签(Tag)过滤
- 给所有不支持原生测试的类添加
@Tag("jvm-only")注解:
import org.junit.jupiter.api.Tag; import org.springframework.boot.test.autoconfigure.data.jpa.DataJpaTest; @Tag("jvm-only") @DataJpaTest class UserRepositoryTest { // 测试代码 }
- 在
pom.xml中配置nativeTest Profile,让Maven Surefire插件排除带有该标签的测试:
<profiles> <profile> <id>nativeTest</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <!-- 排除带有jvm-only标签的测试 --> <excludedGroups>jvm-only</excludedGroups> </configuration> </plugin> <!-- 配置Spring Boot原生测试插件 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <id>native-test</id> <goals> <goal>native-test</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles>
方案二:按类路径/类名规则排除
如果不想给测试类加标签,可以直接通过类的位置或命名规则过滤:
- 把所有不支持原生的测试放在统一包下(比如
com.example.app.jvmtest),或者类名统一后缀(比如*JvmTest.java)。 - 在nativeTest Profile的Surefire配置中添加排除规则:
<profile> <id>nativeTest</id> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <!-- 排除指定包下的所有测试 --> <excludes> <exclude>**/jvmtest/**/*.java</exclude> <!-- 或者排除特定后缀的测试类 --> <exclude>**/*JvmTest.java</exclude> </excludes> </configuration> </plugin> <!-- Spring Boot原生测试插件配置同上 --> </plugins> </build> </profile>
验证方式
- JVM模式下执行测试:直接运行
mvn test,所有测试都会正常执行。 - 原生模式下执行测试:运行
mvn test -PnativeTest,标注的测试会被自动跳过,只执行支持原生的测试类。
内容的提问来源于stack exchange,提问作者edeandrea
相关产品推荐
相关产品推荐

