spring基於MockMvc的controller測試
阿新 • • 發佈:2018-11-27
@Component
public class TestControllerUtil {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
public MvcResult testGetRequest (String url, String contentType) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.get(url)).andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(contentType)).andReturn();
}
/**
* @param url 請求的url 如 "/hello"
* @param contentType 如:text/plain;charset=UTF-8
* @param params MultiValueMap繼承map 實現 MultiValueMap map = new LinkedMultiValueMap<>();
* @throws Exception
*/
public MvcResult testPostRequest(String url, String contentType, MultiValueMap<String, String> params) throws Exception {
return mockMvc.perform(MockMvcRequestBuilders.post(url)
.params(params).accept(contentType))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
}
先寫一個util工具類。以後的測試類都使用這個工具類自動注入。例如:
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloControllerTest {
private Logger logger = LogManager.getLogger(HelloControllerTest.class);
@Autowired
private TestControllerUtil testControllerUtil;
@Before
public void setUp() {
testControllerUtil.setUp();
}
@Test
public void testHelloGEt() throws Exception {
logger.info(testControllerUtil.testGetRequest("/hello", "text/plain;charset=UTF-8").getResponse().getContentAsString());
}
@Test
public void testHelloPost() throws Exception {
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("id", "san");
logger.info(testControllerUtil.testPostRequest("/hello2", "text/plain;charset=UTF-8", map).getResponse().getContentAsString());
}
}
然後執行
最後執行成功。