使用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