spring基于MockMvc的controller测试

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dian853013397/article/details/79908223
@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());

    }

}

然后运行
这里写图片描述

最后运行成功。这里写图片描述

猜你喜欢

转载自blog.csdn.net/dian853013397/article/details/79908223