1. 背景
在每次使用https://start.spring.io/ 創建spring boot後,都會發現它的單元測試好像有點不太一樣,好像是用的junit5,但是我看的pom文件那個測試依賴太長了,看着不爽,如下圖所示。所以我決定還是用之前版本的單元測試
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
2. 使用
2.1 修改pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.2 在test包下創建測試類
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class GmallUserApplicationTests {
@Test
public void contextLoads() {
System.out.println("1111");
}
}
3.注意
- @Test註解的Test包別引錯了,默認的不是引入的junit的Test類
- 由於scope範圍是test,所以如果你想通過依賴其他公共模塊的包(通常公共模塊的包中有公用的依賴)來做到test包的依賴引入是不行的,因爲scope=test的話,只會對當前項目有效