springmvc中使用MockMvc测试controller

Java框架

浏览数:126

2019-3-22

AD:资源代下载服务

示例代码

import com.alibaba.fastjson.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
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;

/**
 * Created by hujunzheng on 2017/6/6.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/spring-common.xml"})
@WebAppConfiguration
public class TestController {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void  setUp( ) {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void test() throws Exception {

        JSONObject params = new JSONObject();
        params.put("userId", 123);
        params.put("page", 1);
        params.put("size", 1);
        String responseString = mockMvc.perform(
                MockMvcRequestBuilders.post("/wallet/records")
                        .accept(MediaType.ALL)
//                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)
//                        .param("userId", "123")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(params.toJSONString())
        )//.andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(print())         //打印出请求和相应的内容
                .andReturn().getResponse().getContentAsString();

        System.out.println(responseString);
    }

}

执行结果

MockHttpServletRequest:
         HTTP Method = POST
         Request URI = /wallet/records
          Parameters = {}
             Headers = {Accept=[*/*], Content-Type=[application/json]}

             Handler:
                Type = com.beiquan.light.web.controller.WalletController
              Method = public java.lang.String com.beiquan.light.web.controller.WalletController.records(com.beiquan.light.web.result.wallet.WalletRecordsReqForm,org.springframework.validation.BindingResult)

               Async:
   Was async started = false
        Async result = null

  Resolved Exception:
                Type = null

        ModelAndView:
           View name = null
                View = null
               Model = null

            FlashMap:

MockHttpServletResponse:
              Status = 200
       Error message = null
             Headers = {Content-Type=[text/plain;charset=UTF-8], Content-Length=[258], Accept-Charset=[big5, big5-hkscs, cesu-8, euc-jp, euc-kr, gb18030, gb2312, gbk, ibm-thai, ibm00858, ibm01140, ibm01141, ibm01142, ibm01143, ibm01144, ibm01145, ibm01146, ibm01147, ibm01148, ibm01149, ibm037, ibm1026, ibm1047, ibm273, ibm277, ibm278, ibm280, ibm284, ibm285, ibm290, ibm297, ibm420, ibm424, ibm437, ibm500, ibm775, ibm850, ibm852, ibm855, ibm857, ibm860, ibm861, ibm862, ibm863, ibm864, ibm865, ibm866, ibm868, ibm869, ibm870, ibm871, ibm918, iso-2022-cn, iso-2022-jp, iso-2022-jp-2, iso-2022-kr, iso-8859-1, iso-8859-13, iso-8859-15, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-9, jis_x0201, jis_x0212-1990, koi8-r, koi8-u, shift_jis, tis-620, us-ascii, utf-16, utf-16be, utf-16le, utf-32, utf-32be, utf-32le, utf-8, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, windows-31j, x-big5-hkscs-2001, x-big5-solaris, x-compound_text, x-euc-jp-linux, x-euc-tw, x-eucjp-open, x-ibm1006, x-ibm1025, x-ibm1046, x-ibm1097, x-ibm1098, x-ibm1112, x-ibm1122, x-ibm1123, x-ibm1124, x-ibm1166, x-ibm1364, x-ibm1381, x-ibm1383, x-ibm300, x-ibm33722, x-ibm737, x-ibm833, x-ibm834, x-ibm856, x-ibm874, x-ibm875, x-ibm921, x-ibm922, x-ibm930, x-ibm933, x-ibm935, x-ibm937, x-ibm939, x-ibm942, x-ibm942c, x-ibm943, x-ibm943c, x-ibm948, x-ibm949, x-ibm949c, x-ibm950, x-ibm964, x-ibm970, x-iscii91, x-iso-2022-cn-cns, x-iso-2022-cn-gb, x-iso-8859-11, x-jis0208, x-jisautodetect, x-johab, x-macarabic, x-maccentraleurope, x-maccroatian, x-maccyrillic, x-macdingbat, x-macgreek, x-machebrew, x-maciceland, x-macroman, x-macromania, x-macsymbol, x-macthai, x-macturkish, x-macukraine, x-ms932_0213, x-ms950-hkscs, x-ms950-hkscs-xp, x-mswin-936, x-pck, x-sjis_0213, x-utf-16le-bom, x-utf-32be-bom, x-utf-32le-bom, x-windows-50220, x-windows-50221, x-windows-874, x-windows-949, x-windows-950, x-windows-iso2022jp]}
        Content type = text/plain;charset=UTF-8
                Body = {"code":"SUCCESS","message":"成功","data":{"page":1,"size":1,"total":2,"list":[{"id":7,"walletId":1,"userId":123,"type":1,"value":1000.00,"origin":"cvs-哈哈","action":"test","desc":"","balance":1000.00,"payCode":"支付宝","createTime":1497006708000}]}}
       Forwarded URL = null
      Redirected URL = null
             Cookies = []
{"code":"SUCCESS","message":"成功","data":{"page":1,"size":1,"total":2,"list":[{"id":7,"walletId":1,"userId":123,"type":1,"value":1000.00,"origin":"cvs-哈哈","action":"test","desc":"","balance":1000.00,"payCode":"支付宝","createTime":1497006708000}]}}

遇到问题

java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted() 

  servlet-api jar包版本的问题。我这里直接依赖上了tomcat中的library,解决该问题。


版权声明:本文原创发表于博客园,作者为小眼儿。本文欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则视为侵权。