JUnit5如何通过Maven命令行基于测试displayName选择执行单个测试
默认无法直接使用mvn test -Dtest="ExampleTestClass#hello"执行对应测试。-Dtest参数默认基于测试类、方法的实际名称做匹配,不会读取@DisplayName注解的自定义值,所以默认配置下该命令不会命中任何测试。
你可以通过以下配置实现基于@DisplayName属性执行测试:
前置依赖要求
- 测试框架使用JUnit 5
- Maven Surefire插件版本升级到
3.0.0-M4及以上,pom.xml配置参考:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.5</version> </plugin> </plugins> </build>
执行命令
执行测试时通过-Djunit.jupiter.displayname.filter参数指定要匹配的@DisplayName值,可搭配-Dtest指定测试类缩小匹配范围:
# 仅执行ExampleTestClass类下DisplayName为hello的测试方法 mvn test -Dtest="ExampleTestClass" -Djunit.jupiter.displayname.filter="hello"
如果需要模糊匹配,也可以使用通配符:
# 执行所有DisplayName包含hello关键词的测试方法 mvn test -Djunit.jupiter.displayname.filter="*hello*"
补充说明
- DisplayName匹配默认大小写敏感,需要大小写不敏感可在参数值前加
(?i)前缀,例如-Djunit.jupiter.displayname.filter="(?i)hello" - 如果多个测试方法的DisplayName完全相同,所有匹配的方法都会被执行
内容的提问来源于stack exchange,提问作者sensenkri
相关产品推荐
相关产品推荐

