国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > Java > 正文

spring-mvc/springboot使用MockMvc對controller進行測試

2024-07-14 08:42:52
字體:
來源:轉載
供稿:網友

網上基本都是參考官方的使用方式,使用了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")));      }}

相信這樣,基本開發(fā)過javaweb的就都能看懂了。通過方法的字面意思應該都能看懂方法含義,如果實在不懂請看源碼或者官方API。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 盐池县| 商南县| 西乡县| 望江县| 崇礼县| 古蔺县| 梁平县| 运城市| 莎车县| 鲁甸县| 丰宁| 嘉义县| 马边| 砚山县| 安新县| 河津市| 九龙坡区| 开鲁县| 论坛| 义马市| 道真| 灵丘县| 涟源市| 界首市| 庄浪县| 忻州市| 三明市| 苏尼特右旗| 乌鲁木齐县| 南康市| 金阳县| 从化市| 溧阳市| 涿鹿县| 崇仁县| 洛扎县| 湾仔区| 普安县| 绥德县| 遂溪县| 珠海市|