junit5 较junit4 有较多的特性加入,比如更方便的参数化测试,JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage。本人在测试junit5以及与spring boot整合的过程中总结以下常见问题:
(1)项目非springboot 项目。
junit 5 maven 基础依赖如下:
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.3.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.3.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.3.2</version>
<scope>test</scope>
</dependency>
其中需重点注意的是版本问题,junit-jupiter-engine和junit-vintage-engine以及junit-platform-launcher版本需要在同一时间发布的版本,一般情况下junit-jupiter-engine和junit-vintage-engine版本一致,junit-platform-launcher版本必须与junit-jupiter-engine和junit-vintage-engine版本发布时间一致的版本,否则测试报错,经常报的错误就是NoSuchMethodError,本质就是三者的版本的发布时间不一致导致。
如果junit 5 需要参数化测试。需添加以下依赖。
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.3.2</version>
<scope>test</scope>
</dependency>
示例如下:
@ParameterizedTest
@ValueSource(strings = {"1", "2", "3"})
public void test(String connectionID) {
System.out.println("connectionID is "+ connectionID);
}
(二) junit 5 与spring boot 整合。
需要添加的maven 依赖。
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.3.2</version>
<scope>test</scope>
</dependency>
如果未添加上述依赖,则导致无法找到单元测试用例,No tests were found.
单元测试示例如下:
@SpringBootTest
@AutoConfigureMockMvc
@ExtendWith(SpringExtension.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class DatasourceControllerTest {
@Test
public void Test(){
}
}
@Test 的import 包为import org.junit.jupiter.api.Test 而非junit4所引用的包。
(3)UT 测试顺序控制
在junit 4中采用 @FixMethodOrder(MethodSorters.NAME_ASCENDING)可根据测试名称控制UT执行顺序,而在junit5 则采用如下注解 @TestMethodOrder(MethodOrderer.OrderAnnotation.class) ,需要在UT测试方法中添加@Order(1)控制其执行顺序。注意此时junit5 的版本需 >= 5.4
(4) maven 运行junit5 用例。
在pom.xml中 <build>增加 maven-surefire-plugin .
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
参考资料: