如何使用Maven Surefire Plugin运行非test命名的JUnit测试方法
问题描述
希望运行测试文件中的所有测试,但Maven Surefire Plugin仅识别名称包含“test”的测试方法。使用JUnit的@Test注解,测试类TokenServiceTest中,带“test”前缀的方法可正常运行,但不带“test”的方法无法被识别。
测试类代码:
class TokenServiceTest { @Test fun testShouldNotRetrieveUserFromToken() { // 此方法因名称含test可运行 setup() generateExpiredToken() val userName = tokenService.getUserFromToken(cookie?.value) assertThat(userName, IsNull.nullValue()) } @Test fun shouldHaveEntityIdentifier() { // 此方法不被maven-surefire-plugin识别 setup() generateTokenWithEntityIdentifier() val entityIdentifier = tokenService.getEntityIdentifierFromToken(cookie?.value) assertThat(entityIdentifier, Is.`is`("12345678")) }
当前pom.xml中插件配置:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M3</version> <configuration> <includes> <include>*Test</include> <include>*TestCase</include> </includes> </configuration> </plugin>
解决方案
方法一:基于JUnit注解识别测试(推荐)
修改maven-surefire-plugin配置,启用JUnit Platform,让插件直接通过@Test注解识别测试方法,不再依赖方法名规则:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M3</version> <configuration> <includes> <include>*Test</include> <include>*TestCase</include> </includes> <useJUnitPlatform>true</useJUnitPlatform> </configuration> </plugin>
若项目未引入JUnit Jupiter依赖,需在dependencies中添加:
<dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.9.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.9.2</version> <scope>test</scope> </dependency>
方法二:自定义方法名匹配规则
如果不想切换到JUnit Platform,可修改插件的方法名匹配模式,允许所有方法名:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M3</version> <configuration> <includes> <include>*Test</include> <include>*TestCase</include> </includes> <testNamePattern>.*</testNamePattern> </configuration> </plugin>
.*表示匹配任意方法名,只要测试类符合*Test/*TestCase规则,所有带@Test注解的方法都会被执行。
内容的提问来源于stack exchange,提问作者rshncp
相关产品推荐
相关产品推荐

