You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 06:20:22