Spring Boot Test 簡(jiǎn)介
Spring Boot提供了大量的實(shí)用的注解來(lái)幫助我們測(cè)試程序。針對(duì)測(cè)試支持由兩個(gè)模塊提供,spring-boot-test包含核心項(xiàng)目,而spring-boot-test-autoconfigure支持測(cè)試的自動(dòng)配置。
大多數(shù)開(kāi)發(fā)人員只使用spring-boot-starter-test即可,它會(huì)導(dǎo)入兩個(gè)Spring Boot測(cè)試模塊以及JUnit,AssertJ,Hamcrest和一些其他有用的庫(kù)。
搭建測(cè)試環(huán)境
? 基于上文中的例子,我們來(lái)搭建測(cè)試環(huán)境。
1、在pom.xml文件中,添加spring-boot-starter-test的依賴,它包含了一系列的測(cè)試庫(kù)(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、我們簡(jiǎn)單的先針對(duì)Controller層進(jìn)行單元測(cè)試。測(cè)試Spring MVC只需在對(duì)應(yīng)的測(cè)試類上添加@WebMvcTest注解即可。由于是基于Spring Test環(huán)境下的單元測(cè)試,請(qǐng)不要忘記添加@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、運(yùn)行IndexControllerTest.java中的testIndex()方法,即可看到測(cè)試結(jié)果。
本文示例程序請(qǐng)點(diǎn)此獲取。
詳細(xì)資料請(qǐng)參考Spring Boot官網(wǎng)。