WebMvcTest to Swagger Yaml (2)

25 July 2020

이번은 MockMvc 필터를 통해 Test Case의 request와 response를 parsing하는 방법을 알아보도록 합니다.

아래와 같이 필터를 선언해주도록 합니다.

package org.shashaka.io.utils;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

import javax.servlet.*;

@Slf4j
@AllArgsConstructor
public class SwaggerDocFilter implements Filter {

    private final SwaggerGenerator swaggerGenerator;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

        MockHttpServletRequest mockHttpServletRequest = (MockHttpServletRequest) request;
        chain.doFilter(request, response);

        MockHttpServletResponse mockHttpServletResponse = (MockHttpServletResponse) response;

        swaggerGenerator.addModel(mockHttpServletRequest, mockHttpServletResponse);
    }

    @Override
    public void destroy() {

    }
}
MockMvc가 수행될 때, MockHttpServletRequest와 MockHttpServletResponse를 parsing하여 해당 값으로 예제를 만들어볼 수 있습니다.
아래와 같이 method, url, parameters, headers, body 등 각각의 값을 가져올 수 있는 것을 확인할 수 있습니다.

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /swagger/post/1
       Parameters = {first=[myFirst], latest=[myLatest]}
          Headers = [Content-Type:"application/json", Content-Length:"88"]
             Body = 
    Session Attrs = {}

Handler:
             Type = org.shashaka.io.controller.SwaggerPostController
           Method = org.shashaka.io.controller.SwaggerPostController#postMethod(Integer, String, String, PostRequest)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

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

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = {"name":"namemyLatestmyFirst"}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

위 값을 parsing하여 원하는 포맷으로 넣어주도록 합니다.
전체 소스코드는 아래에서 확인할 수 있습니다.
https://gitlab.com/shashaka/tc2swagger