본문 바로가기
공부/프로젝트

restdocs를 사용해보자

by JERO__ 2022. 7. 29.

RestDocs이란?

Spring REST Docs helps you to document RESTful services. It combines hand-written documentation written with Asciidoctor and auto-generated snippets produced with Spring MVC Test. This approach frees you from the limitations of the documentation produced by tools like Swagger. It helps you to produce documentation that is accurate, concise, and well-structured. This documentation then allows your users to get the information they need with a minimum of fuss.

  1. Spring REST 문서는 RESTful 서비스를 문서화하는 데 도움이 됩니다.
  2. Asciodoctor로 작성된 수기 문서와 Spring MVC Test로 제작된 자동 생성 스니펫을 결합
  3. 이러한 접근 방식을 통해 스웨거와 같은 툴에서 생성되는 문서의 제약에서 벗어날 수 있다.
  4. 프로덕션 코드와 분리하여 문서 자동화
  5. 신뢰도 높은 API

왜 사용할까?

  1. 실제 코드에 추가되는 코드가 없다.
    • 프로덕션 코드와 분리되어있기 때문에 Swagger 같이 Config 설정 코드나 어노테이션이 우리의 프로덕션 코드를 더럽힐 일이 없다.
  2. 테스트가 성공해야 문서 작성된다.
    • Spring REST Docs는 테스트가 성공하지 않으면 문서를 만들 수 없다.
    • Spring REST Docs로 문서를 만든다는 것은 API의 신뢰도를 높이고 더불어 테스트 코드의 검증을 강제로 하게 만드는 좋은 문서화 도구이다.

build.gradle 설정

환경

  • Spring Boot 2.7.1
  • Gradle 7.4.1
  • Java 11
  • Junit5

1. Plugin 추가

  • org.asciidoctor.jvm.convertgradle 7부터 org.asciidoctor.convert가 아닌 org.asciidoctor.jvm.convert를 사용해야 한다.
    • adoc 파일 변환
    • build 디렉도리에 복사
plugins {
	id 'org.asciidoctor.jvm.convert' version '3.3.2'
}

plugins { id 'org.asciidoctor.jvm.convert' version '3.3.2' }

2. 스니펙 디렉토리 설정

스니펫 : 문서의 조각

RestDocs에 대한 명세내역을 코드에 작성한 후 테스트 케이스가 정상적으로 실행이 되었다면 RestDocs의 내용을 기준으로 Snippet 문서가 생성되는데, Gradle 기준으로 build/generated-snippets 디렉토리 하위에 생성된다

ext{
	set('snippetsDir', file("build/generated-snippets"))
}
  • ext : 전역변수 설정
  • gradle의 스니펫은 build/generated-snippets에 생성된다. 스니펫 생성 디렉토리를 snippetsDir라는 전역변수에 담는다.

종류

  • curl-request.adoc : 호출에 대한 curl 명령을 포함 하는 문서
  • httpie-request.adoc : 호출에 대한 http 명령을 포함 하는 문서
  • http-request.adoc : http 요청 정보 문서
  • http-response.adoc : http 응답 정보 문서
  • request-body.adoc : 전송된 http 요청 본문 문서
  • response-body.adoc : 반환된 http 응답 본문 문서
  • request-parameters.adoc : 호출에 parameter 에 대한 문서
  • path-parameters.adoc : http 요청시 url 에 포함되는 path - parameter 에 대한 문서
  • request-fields.adoc : http 요청 object 에 대한 문서
  • response-fields.adoc : http 응답 object 에 대한 문서

3. asciidoctor

asciidoctor : 스니펫을 이용하여 HTML을 생성하는 도구.

  • 기존에 존재하는 docs를 삭제
  • 문서옮기기 build/docs/asciidoc → src/main/resources/static
configurations {
	asciidoctorExtensions
}

tasks.named('asciidoctor') {
	configurations 'asciidoctorExtensions'
	baseDirFollowsSourceFile()
	inputs.dir snippetsDir
	dependsOn test
}

asciidoctor.doFirst {
	delete file('src/main/resources/static/docs')
}

4. copyDocument

task createDocument(type: Copy) {
    dependsOn asciidoctor
    from file("build/docs/asciidoc")
    into file("src/main/resources/static")
}

5. bootJar

  • bootJar 실행시 생성되도록 변경
bootJar {
    dependsOn createDocument
    from("${asciidoctor.outputDir}") {
        into 'static/docs'
    }
}

6. 의존성추가

dependencies {
    testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
}

진행과정을 알아보자

테스트 코드를 실행한다.

  1. 테스트 코드가 성공하면 스니펫이 생성된다.
  2. asciidoctor가 생성된 스니펫을 사용하여 문서를 작성한다.
  3. 2번 문서를 기반으로 HTML 문서가 생성된다.
  4. HTML문서를 접근가능한 main/resources/static으로 복사한다.

우리는 무엇을 해야할까?

1. 테스트코드를 통해 스니펫 생성한다.

  • MockMvc : @WebMvcTest
  • restassured : @SpringBootTest

2. asciidoctor로 HTML 문서를 만든다.

어떤 기준으로 HTML API 문서로 만들지 설정해주어야 한다. src/docs/asciidoc 하위에 adoc파일을 만든다. 네이밍은 자유이다.

예시

  • index.adoc
= NAEPYEON(내편) Application API Document
:doctype: book
:icons: font
:source-highlighter: highlightjs
:toc: left
:toclevels: 3
:sectlinks:

include::auth.adoc[]
include::members.adoc[]
include::teams.adoc[]
include::rollingpapers.adoc[]
include::messages.adoc[]
include::errorCodes.adoc[]
  • auth.adoc
== 로그인

=== 로그인(/api/v1/login)
operation::auth-controller-test/login[snippets='http-request,http-response']

댓글