ysk(0soo)
Lifealong
ysk(0soo)
전체 방문자
오늘
어제
  • 분류 전체보기 (238)
    • Java (50)
      • whiteship-java-study (11)
      • Java (28)
      • time (6)
    • Spring (68)
      • JPA (15)
      • Spring (1)
      • SpringBoot (1)
      • SpringMVC (6)
      • Spring Security (22)
      • Jdbc (1)
      • RestDocs (14)
      • log (6)
    • Kotlin (3)
    • Web (2)
      • nginx (1)
    • Database (14)
      • MySQL (5)
      • PostgreSQL (1)
      • SQL (1)
      • Redis (4)
    • C, C++ (0)
    • Git (1)
    • Docker (2)
    • Cloud (3)
      • AWS (3)
    • 도서, 강의 (0)
      • t5 (0)
    • 기타 (7)
      • 프로그래밍 (1)
    • 끄적끄적 (0)
    • CS (14)
      • 운영체제(OS) (2)
      • 자료구조(Data Structure) (9)
    • 하루한개 (12)
      • 우아한 테크코스-10분테코톡 (12)
    • 스터디 (12)
      • 클린 아키텍처- 로버트마틴 (2)
      • JPA 프로그래밍 스터디 (10)
    • 테스트 (34)
      • JUnit (19)
      • nGrinder (2)
      • JMeter (0)
    • Infra (3)
    • 프로그래머스 백엔드 데브코스 3기 (0)
    • 디자인 패턴 (3)
    • Issue (4)
    • system (1)
      • grafana (0)
      • Prometheus (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • github

공지사항

인기 글

태그

  • nginx basic auth
  • 가상 스레드
  • LocalDateTime
  • 동일성
  • nGrinder
  • mysql
  • tree
  • 동시성 제어
  • querydsl
  • scope value
  • node exporter basic auth
  • 가상 스레드 예외 핸들링
  • 정규표현식
  • 트랜잭션
  • StructuredConcorrency
  • DataJpaTest
  • 동등성
  • AccessDecisionVoter 커스텀
  • java
  • restdocs enum
  • 인가(Authorization) 처리
  • AuthenticationException
  • AccessDecisionManager
  • UserDetailsService
  • VirtualThread Springboot
  • FilterSecurityInterceptor
  • restdocs custom
  • jpa
  • junit5
  • 구조화된 동시성

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ysk(0soo)

Lifealong

Spring/RestDocs

Restdocs pretty print, header 제거

2023. 1. 29. 17:56

Restdocs pretty print - 이쁘게 출력하기

기본적으로 요청과 응답의 body가 텍스트로 쭉 나열된다. 크기가 작으면 상관 없지만, json 객체가 커진다면 제대로 확인하기 힘들어진다.

pretty print 기능은 말 그대로 예쁘게 포메팅해준다.

스니펫을 모아 DocumentFilter를 만들때 넣어주면 된다.

RestDocumentationFilter restDocumentationFilter = document(
        "simple-read",
      preprocessRequest(prettyPrint()),
        preprocessResponse(prettyPrint()),
        simplePathParameterSnippet(),
        simpleRequestParameterSnippet(),
        simpleResponseFieldsSnippet()
);

기본 설정으로 사용하려면 초기화할때 넣어준다.

@BeforeEach
void setUpRestDocs(RestDocumentationContextProvider restDocumentation) {
    Filter documentationConfiguration = documentationConfiguration(restDocumentation)
            .operationPreprocessors()
            .withRequestDefaults(prettyPrint())
            .withResponseDefaults(prettyPrint());
​
    this.spec = new RequestSpecBuilder()
            .addFilter(documentationConfiguration)
            .build();
}

불필요한 헤더 제거 - Restdocs header 제거

API문서에 불필요한 헤더가 포함되어 보인다. 이를 없애줄 수도 있다.

@BeforeEach
void setUpRestDocs(RestDocumentationContextProvider restDocumentation) {
    Filter documentationConfiguration = documentationConfiguration(restDocumentation)
            .operationPreprocessors()
            .withRequestDefaults(prettyPrint())
            .withResponseDefaults(
                    removeHeaders(
                            "Transfer-Encoding",
                            "Date",
                            "Keep-Alive",
                            "Connection"
                    ),
                    prettyPrint()
            );
​
    this.spec = new RequestSpecBuilder()
            .addFilter(documentationConfiguration)
            .build();
}

매개변수화된 출력 디렉토리

DocumentFilter를 만들면서 어떤 디렉토리에 저장할지 정해진다.

RestDocumentationFilter restDocumentationFilter = document(
        "simple-read", // 디렉토리명
        simplePathParameterSnippet(),
        simpleRequestParameterSnippet(),
        simpleResponseFieldsSnippet()
);

일일이 이름을 정해줘야 한다. 개발자의 숙명이지만 항상 어렵다.

이런 고통을 덜어주는 기능이 있다. 미리 정해진 변수를 적어주면 클래스명과 메소드명 그리고 스텝 순서를 불러올 수 있다.

ParameterDescription

{methodName} 메소드명
{method-name} 메소드명을 kebab-case로 포메팅 한다
{meth 메소드명을 snake_case로 포메팅 한다
{ClassName} 클래스명
{class-name} 클래스명을 kebab-case로 포메팅 한다
{class_name} 클래스명을 snake_case로 포메팅 한다
{step} 현재 테스트의 실행 순서를 불러온다

테스트를 나눠서 애매한 경우도 처리 가능하다. 테스트 메소드를 기준으로 이름을 만들어주기 때문이다.

RestDocumentationFilter restDocumentationFilter = document(
        "{class-name}/{method-name}",
        preprocessResponse(prettyPrint()),
        simplePathParameterSnippet(),
        simpleRequestParameterSnippet(),
        simpleResponseFieldsSnippet()
);
​
@Test
void test1() {
    RequestSpecification given = RestAssured.given(this.spec)
                .baseUri(BASE_URL)
                .port(port)
                .pathParam("id", 1)
                .queryParam("name", "name")
                .filter(restDocumentationFilter);
}
​
@Test
void test2() {
    RequestSpecification given = RestAssured.given(this.spec)
                .baseUri(BASE_URL)
                .port(port)
                .pathParam("id", 1)
                .queryParam("name", "name")
                .filter(restDocumentationFilter);
}

위의 경우는 클래스명/test1과 클래스명/test2가 만들어진다.

MockMvc와 REST Assured에서만 사용 가능하고, WebTestClient는 사용 불가능하다.

배열 표현 - Array

배열은 a.b[].c와 같이 표현할 수 있다.

이외에도 여러가지 표현식이 있는데, JSON Field Paths를 참고하자.

일반적인 경우에는 문제가 없겠지만, 배열을 동적으로 생성하거나 해야 하는 경우에 표현이 애매할 수 있다. 이럴 때 a.*[].c와 같이 와일드 카드로 처리해줄 수 있다.

참조

  • https://velog.io/@dae-hwa/Spring-REST-Docs-%EC%82%B4%ED%8E%B4%EB%B3%BC%EB%A7%8C%ED%95%9C-%EA%B8%B0%EB%8A%A5%EB%93%A4
저작자표시 비영리 (새창열림)

'Spring > RestDocs' 카테고리의 다른 글

Restdocs header 설정  (0) 2023.01.31
REST Docs에 DTO Bean Validation 담기  (0) 2023.01.29
RestDocs Custom - 문서 커스텀  (1) 2023.01.29
RestDocs 문서 분리 방법 - adoc, mustache  (0) 2023.01.29
Restdocs Enum 공통코드 문서화 방법 - Enum 문서화  (0) 2023.01.29
    'Spring/RestDocs' 카테고리의 다른 글
    • Restdocs header 설정
    • REST Docs에 DTO Bean Validation 담기
    • RestDocs Custom - 문서 커스텀
    • RestDocs 문서 분리 방법 - adoc, mustache
    ysk(0soo)
    ysk(0soo)
    백엔드 개발을 좋아합니다. java kotlin spring, infra 에 관심이 많습니다. email : kim206gh@naver.com github : https://github.com/devysk

    티스토리툴바