使用MockMVC进行带有参数的post访问
package com.springboot.demo; 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.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @RunWith(SpringRunner.class) @SpringBootTest public class HelloWorldTest { private MockMvc mockMvc; //启用web上下文 @Autowired private WebApplicationContext context; //使用上下文构建mockMvc @Before public void setUp(){ mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } //存在controller,其访问路径为/hello,且带有一个参数name @Test public void getHello() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/hello?name=zhangsan") .accept(MediaType.APPLICATION_JSON_UTF8)).andDo(print()); } }
运行该单元测试,其运行结果为
MockHttpServletRequest: HTTP Method = POST Request URI = /hello Parameters = {name=[zhangsan]} Headers = {Accept=[application/json;charset=UTF-8]} Body = <no character encoding set> Session Attrs = {} Handler: Type = null Async: Async started = false Async result = null Resolved Exception: Type = org.springframework.web.HttpRequestMethodNotSupportedException ModelAndView: View name = null View = null Model = null FlashMap: Attributes = null MockHttpServletResponse: Status = 405 Error message = Request method 'POST' not supported Headers = {Allow=[GET]} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = []
从上面我们可以看到访问方式,访问路径,参数,访问头,ModelAndView