Spring Boot Test 簡介
Spring Boot提供了大量的實用的注解來幫助我們測試程序。針對測試支持由兩個模塊提供,spring-boot-test
包含核心項目,而spring-boot-test-autoconfigure
支持測試的自動配置。
大多數開發人員只使用spring-boot-starter-test
即可,它會導入兩個Spring Boot測試模塊以及JUnit,AssertJ,Hamcrest和一些其他有用的庫。
搭建測試環境
? 基于上文中的例子,我們來搭建測試環境。
1、在pom.xml
文件中,添加spring-boot-starter-test
的依賴,它包含了一系列的測試庫(JUnit?、Spring Test 、AssertJ?、Hamcrest、Mockito?、JSONassert?、JsonPath?)。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、我們簡單的先針對Controller層進行單元測試。測試Spring MVC只需在對應的測試類上添加@WebMvcTest
注解即可。由于是基于Spring Test環境下的單元測試,請不要忘記添加@RunWith(SpringRunner.class)
注解。
在test\java\com\jason\web
目錄下新建IndexControllerTest.java
文件。
package com.jason.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(IndexController.class)
public class IndexControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void testIndex() throws Exception {
this.mvc.perform(get("/index").accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk()).andExpect(content().string("Hello, Spring Boot!"));
}
}
3、運行IndexControllerTest.java
中的testIndex()
方法,即可看到測試結果。
本文示例程序請點此獲取。
詳細資料請參考Spring Boot官網。