日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

spring-mvc springboot 使用MockMvc对controller进行测试

發布時間:2025/7/14 c/c++ 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring-mvc springboot 使用MockMvc对controller进行测试 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

網上基本都是參考官方的使用方式,使用了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的啟動類名。 @WebAppConfiguration public class ApplicationTests {@Autowiredprivate WebApplicationContext context;private MockMvc mvc;@Beforepublic void setUp() throws Exception {// mvc = MockMvcBuilders.standaloneSetup(new TestController()).build();mvc = MockMvcBuilders.webAppContextSetup(context).build();//建議使用這種}@Testpublic 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。

轉載于:https://www.cnblogs.com/qlong8807/p/7121522.html

總結

以上是生活随笔為你收集整理的spring-mvc springboot 使用MockMvc对controller进行测试的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。