我在Spring Boot+Kotlin环境下尝试运行Junit5
首先
在进行单元测试时,决定使用更新的JUnit5,并遇到了一些困难,所以将其作为备忘录发布。
开发环境
Spring Boot 2.3.4
kotlin 1.3.7
Gradle
JUnit5
Spring Boot 2.3.4
Kotlin 1.3.7
Gradle
JUnit5
在上述版本中,我们将逐步添加用于测试的配置。
更改Gradle配置文件
dependencies {
- testImplementation 'org.springframework.boot:spring-boot-starter-test'
+ testCompile('org.springframework.boot:spring-boot-starter-test') {
+ exclude module: 'org.junit.vintage'
+ }
+ testImplementation('org.junit.jupiter:junit-jupiter:5.4.0')
}
+ test {
+ useJUnitPlatform()
+ }
按顺序来,
添加JUnit5
+ testImplementation('org.junit.jupiter:junit-jupiter:5.4.0')
只有添加JUnit5仍然会导致与JUnit4的依赖关系错误发生。
解决JUnit4的依赖关系
- testImplementation 'org.springframework.boot:spring-boot-starter-test'
+ testCompile('org.springframework.boot:spring-boot-starter-test') {
+ exclude module: 'org.junit.vintage'
+ }
如果使用starter的话,JUnit4会被默认引入,并且通过排除’org.junit.vintage’来让它正常工作。
JUnit Vintage是一个库,用于在平台上执行基于JUnit3和JUnit4的测试的TestEngine提供。
3. 添加使用JUnit平台的配置设置
+ test {
+ useJUnitPlatform()
+ }
设置已完成。
最终
或许很显而易见,JUnit5与JUnit4相比有一些变化,并且还需要注意一些事项。
在JUnit 5中,引入了新的org.junit.jupiter包来使用注释和类。
例如:org.junit.Test被改为org.junit.jupiter.api.Test。
・标注也进行了各种更改。
- @Test(expected = Exception.class)
+ @Test
- @Before
+ @BeforeEach
- @After
+ @AfterEach
- @BeforeClass
+ @BeforeAll
- @AfterClass
+ @AfterAll
- @Ignore
+ @Disabled
- @Category
+ @Tag
- @Rule
- @ClassRule
+ @ExtendWith
+ @RegisterExtension
JUnit 5的断言已经包含在org.junit.jupiter.api.Assertions中。
例如,存在一些通过参数顺序的更改或通过注解替代的断言,比如assertEquals()或assertNotNull()。
据说JUnit5还包含了其他提高可维护性和其他方便功能的功能,并且我们希望积极地使用它。