網上基本都是參考官方的使用方式,使用了import static,個人感覺這種方式特別不好,代碼提示性不友好。所以在此進行說明,也方便自己以后使用。
1. 引入spring-test相關jar包,springboot只需引入spring-boot-starter-test即可
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
2. 寫好controller,開始寫test類
import org.front.server.Application;import org.front.server.web.control.TestController;import org.hamcrest.Matchers;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.SpringApplicationConfiguration;import org.springframework.http.MediaType;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;import org.springframework.test.web.servlet.result.MockMvcResultHandlers;import org.springframework.test.web.servlet.result.MockMvcResultMatchers;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import org.springframework.web.context.WebApplicationContext;//網上很多會在這里使用import static,主要導入的是MockMvcRequestBuilders,MockMvcResultMatchers,Matchers這三個類中的方法。/** * @author zz * @date 2017年7月4日 * */@RunWith(SpringJUnit4ClassRunner.class)//@SpringApplicationConfiguration(classes = MockServletContext.class)//這個測試單個controller,不建議使用@SpringApplicationConfiguration(classes = Application.class)//這里的Application是springboot的啟動類名。@WebAppConfigurationpublic class ApplicationTests { @Autowired private WebApplicationContext context; private MockMvc mvc; @Before public void setUp() throws Exception { // mvc = MockMvcBuilders.standaloneSetup(new TestController()).build(); mvc = MockMvcBuilders.webAppContextSetup(context).build();//建議使用這種 } @Test public void test1() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/data/getMarkers") .contentType(MediaType.APPLICATION_JSON_UTF8) .param("lat", "123.123").param("lon", "456.456") .accept(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("SUCCESS"))); }}
相信這樣,基本開發過javaweb的就都能看懂了。通過方法的字面意思應該都能看懂方法含義,如果實在不懂請看源碼或者官方API。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選