Spring Boot 的測試類庫
Spring Boot 提供了許多實用工具和注解來幫助測試應用程序,主要包括以下兩個模塊。
-
spring-boot-test:支持測試的核心內容。
-
spring-boot-test-autoconfigure:支持測試的自動化配置。
開發進行只要使用 spring-boot-starter-test 啟動器就能引入這些 Spring Boot 測試模塊,還能引入一些像 JUnit, AssertJ, Hamcrest 及其他一些有用的類庫,具體如下所示。
- JUnit:Java 應用程序單元測試標准類庫。
- Spring Test & Spring Boot Test:Spring Boot 應用程序功能集成化測試支持。
- AssertJ:一個輕量級的斷言類庫。
- Hamcrest:一個對象匹配器類庫。
- Mockito:一個Java Mock測試框架,默認支付 1.x,可以修改為 2.x。
- JSONassert:一個用於JSON的斷言庫。
- JsonPath:一個JSON操作類庫。
下面是 Maven 的依賴關系圖。

以上這些都是 Spring Boot 提供的一些比較常用的測試類庫,如果上面的還不能滿足你的需要,你也可以隨意添加其他的以上沒有的類庫。
測試 Spring Boot 應用程序
添加 Maven 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.5.10.RELEASE</version>
<scope>test</scope>
</dependency>
1、 要讓一個普通類變成一個單元測試類只需要在類名上加入 @SpringBootTest 和 @RunWith(SpringRunner.class) 兩個注釋即可。
2、 在測試方法上加上 @Test 注釋。
如果測試需要做 REST 調用,可以 @Autowire 一個 TestRestTemplate。
@RunWith(SpringRunner.class)
@SpringBootTest
public class BBTestAA {
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void testDemo() {
...
}
}
GET請求測試
@Test
public void get() throws Exception {
Map<String,String> multiValueMap = new HashMap<>();
multiValueMap.put("username","Java技術棧");
ActResult result = testRestTemplate.getForObject("/test/getUser?username={username}",ActResult.class,multiValueMap);
Assert.assertEquals(result.getCode(),0);
}
POST請求測試
@Test
public void post() throws Exception {
MultiValueMap multiValueMap = new LinkedMultiValueMap();
multiValueMap.add("username","Java技術棧");
ActResult result = testRestTemplate.postForObject("/test/post",multiValueMap,ActResult.class);
Assert.assertEquals(result.getCode(),0);
}
文件上傳測試
@Test
public void upload() throws Exception {
Resource resource = new FileSystemResource("/home/javastack/test.jar");
MultiValueMap multiValueMap = new LinkedMultiValueMap();
multiValueMap.add("username","Java技術棧");
multiValueMap.add("files",resource);
ActResult result = testRestTemplate.postForObject("/test/upload",multiValueMap,ActResult.class);
Assert.assertEquals(result.getCode(),0);
}
文件下載測試
@Test
public void download() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.set("token","javastack");
HttpEntity formEntity = new HttpEntity(headers);
String[] urlVariables = new String[]{"admin"};
ResponseEntity<byte[]> response = testRestTemplate.exchange("/test/download?username={1}",HttpMethod.GET,formEntity,byte[].class,urlVariables);
if (response.getStatusCode() == HttpStatus.OK) {
Files.write(response.getBody(),new File("/home/javastack/test.jar"));
}
}
