Spring Boot 單元測試詳解+實戰教程
阿新 • • 發佈:2019-01-23
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"));
}
}
掃描關注我們的微信公眾號,乾貨每天更新。