MockMvc 來自Spring Test,它允許您通過一組方便的builder類向 DispatcherServlet 發送HTTP請求,並對結果作出斷言。請注意,@AutoConfigureMockMvc 與@SpringBootTest 需要一起注入一個MockMvc 實例。在使用@SpringBootTest 時候,我們需要創建整個應用程序上下文。
示例代碼:
import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class)//表示使用Spring Test組件進行單元測試 @Transactional//回滾所有增刪改 @SpringBootTest @AutoConfigureMockMvc//注入一個MockMvc實例 public class DingControllerTest { private final static Logger logger = LoggerFactory.getLogger(DingControllerTest.class); @Autowired private MockMvc mockMvc; @Test @Rollback(false)//取消回滾public void getSignature() throws Exception { String responseString = mockMvc.perform( post("/ding/getSignature")//請求的url,請求的方法是post .contentType(MediaType.APPLICATION_JSON)//數據的格式 .param("url", "https://www.baidu.com/")//添加參數 ).andExpect(status().isOk())//返回的狀態是200 .andExpect(MockMvcResultMatchers.jsonPath("$.state").value(1)) //判斷某返回值是否符合預期 .andDo(print())//打印出請求和相應的內容 .andReturn().getResponse().getContentAsString();//將相應的數據轉換為字符串 logger.info("post方法/ding/getSignature,{}", responseString); } }
官方文檔:
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-with-mock-environment
