spring基于MockMvc的controller测试

@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());

    }

}

然后运行
这里写图片描述

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值