如何使用spring-test-mvc打印请求体

时间:2015-10-08 10:34:02

标签: spring-boot spring-test-mvc

我使用spring-test-mvc来测试我的控制器,但我找不到打印请求体的方法,这非常不方便。

使用MockMvcResultHandlers.print()

mvc.perform(put("/payment/1234")
    .content("{\"amount\":2.3")
    .contentType(MediaType.APPLICATION_JSON))
    .andDo(print());

我找到了一些身体信息,但找不到身体部位:

MockHttpServletRequest:
     HTTP Method = PUT
     Request URI = /payment/1234
      Parameters = {}
         Headers = {Content-Type=[application/json]}

         Handler:
            Type = com.restbucks.ordering.rest.PaymentResource
          Method = public org.springframework.hateoas.Resource<com.restbucks.ordering.domain.Payment> com.restbucks.ordering.rest.PaymentResource.handle(com.restbucks.ordering.commands.MakePaymentCommand)

           Async:
   Async started = false
    Async result = null

更新

在阅读了一些源代码后,似乎我应该扩展MockMvcResultHandlers来添加一些打印项?

//PrintingResultHandler.java
protected void printRequest(MockHttpServletRequest request) throws Exception {
    this.printer.printValue("HTTP Method", request.getMethod());
    this.printer.printValue("Request URI", request.getRequestURI());
    this.printer.printValue("Parameters", getParamsMultiValueMap(request));
    this.printer.printValue("Headers", getRequestHeaders(request));
    // add body print?
}

更新 概念证明代码:

public static class CustomMockMvcResultHandlers {

    public static ResultHandler print() {
        return new ConsolePrintingResultHandler();
    }


    /**
     * Have to copy this class from spring
     */
    private static class ConsolePrintingResultHandler extends PrintingResultHandler {

        public ConsolePrintingResultHandler() {
            super(new ResultValuePrinter() {

                @Override
                public void printHeading(String heading) {
                    System.out.println();
                    System.out.println(String.format("%20s:", heading));
                }

                @Override
                public void printValue(String label, Object value) {
                    if (value != null && value.getClass().isArray()) {
                        value = CollectionUtils.arrayToList(value);
                    }
                    System.out.println(String.format("%20s = %s", label, value));
                }


            });


        }

        @Override
        protected void printRequest(MockHttpServletRequest request) throws Exception {
            super.printRequest(request);
            getPrinter().printValue("Body", getContentAsString(request));
        }

        private String getContentAsString(MockHttpServletRequest request) throws IOException {
            BufferedReader reader = request.getReader();

            StringBuilder builder = new StringBuilder();
            String aux;

            while ((aux = reader.readLine()) != null) {
                builder.append(aux);
            }

            return builder.toString();
        }
    }
}

1 个答案:

答案 0 :(得分:4)

我相信现在可以使用Spring Framework 5.0 M3:

  

如果在模拟请求中设置了字符编码,Spring MVC Test中的print()和log()方法现在会打印请求正文。

基于this Jira ticket

release notes

中也提到过