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>
同時,測試類的Demo如下,其中@SpringBootTest表示將該類作為Spring的測試類,加載到spring容器中,必不可少。
import static org.junit.jupiter.api.Assertions.assertEquals; import example.util.Calculator; import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MyFirstJUnitJupiterTests { private final Calculator calculator = new Calculator(); @Test void addition() { assertEquals(2, calculator.add(1, 1)); } }
如果項目中要使用舊版的Junit4,那么在pom文件中要刪除掉“<exclusions>”這個對舊版本的支持,同時導入Junit4的相關依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
在測試類中,不要忘了添加@Runwith(SpringRunner.class)注解,有時候@Test的導入的包也有影響,需要注意
文檔:
Junit5:https://junit.org/junit5/docs/current/user-guide/#writing-tests