티스토리 뷰

반응형

본 글은 rest docs 를 적용하기 위한 방법 및 적용하면서 발생한 문제, 해결 방법 등을 정리한 것입니다.

 


rest docs 적용방법

1) test 코드 작성

2) snippet 파일 생성 

3) adoc 파일생성 + snippet 파일 import

4) html 파일로 변환

5) 최종화면 

 

※ 전체 코드는 하단 git 참고 

 

 

 

 

 

들어가기 전

spring rest docs 을 적용하기 위한 코드가 필요하다. 간단하게 member에 대한 CRUD 를 작성하였다.

 

 

 

1. test 코드 작성

GET Member에 대한 testcase

@Test
void getMemberTest() throws Exception {
    mockMvc.perform(get("/member/{name}", "john"))
            .andDo(print())
            .andExpect(jsonPath("$.name", is("john")));
}

CREATE Member에 대한 testcase

@Test
void createMemberTest() throws Exception {
    mockMvc.perform(post("/member")
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                    .content("{\n" +
                            "    \"name\":\"jessi\",\n" +
                            "    \"grade\":\"junior\",\n" +
                            "    \"year\":2\n" +
                            "}"))
            .andDo(print())
            .andExpect(status().isOk());
}

 

 

2. snippet 파일 작성하기

snippets 파일 생성을 위한 gradle 설정

ext{
   snippetDir = file('build/generated-snippets') //snippets 파일을 저장할 디렉토리 생성
}

test {
   useJUnitPlatform()
   outputs.dir snippetDir //생성된 파일을 미리 생성한 디렉토리(build/generated-snippets)에 저장
}
dependencies {
    ....
    
   //spring rest docs 을 이용하기 위한 라이브러리
   testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc' 
}

 

 

테스트 수행 시, 자동으로 sinppets 파일을 생성하도록 test파일 설정

//Spring REST Docs 자동 설정 어노테이션 
@AutoConfigureRestDocs
...
class MemberControllerTest {

   ...

    @Test
    void getMemberTest() throws Exception {
        mockMvc.perform(get("/member/{name}", "john"))
                .andDo(print())
                .andDo(document("getMember")) //test 수행시 snippets 로 생성해줌 ( 파일명 )
                .andExpect(jsonPath("$.name", is("john")));
    }

    @Test
    void createMemberTest() throws Exception {
        mockMvc.perform(post("/member")
                        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                        .content("{\n" +
                                "    \"name\":\"jessi\",\n" +
                                "    \"grade\":\"junior\",\n" +
                                "    \"year\":2\n" +
                                "}"))
                .andDo(print())
                .andDo(document("createMember")) //test 수행시 snippets 로 생성해줌 ( 파일명 )
                .andExpect(status().isOk());
    }
    
    ...
}

 

gradle 빌드 후, test 수행한 결과 

 

 

3. adoc 파일생성 + snippet 파일 import

Rest API 문서의 메인 파일을 생성한다. 

- src/docs/asciidoc 디렉토리 생성 후, index.adoc 생성

index.adoc 내용 작성

- include::{snippets} 를 이용하여 생성한 snippets 파일을 추가한다.

 

 

4. html 파일로 변환

bootJar 파일에 index.html 문서를 추가하기 위한 build.gradle 설정

plugins {
   ...
   
   id 'org.asciidoctor.jvm.convert' version '3.3.2' //asciidoctor plugin 추가
}

... 

asciidoctor{ //asciidoctor 설정 task
   inputs.dir snippetDir //snippets 디렉토리를 입력으로 함
   dependsOn test // test task를 의존하도록 하여, 문서 생성 전에 test를 수행하도록 함
}

bootJar{ //springboot를 이용한 jar 파일 생성 시 필요한 설정 task
   dependsOn asciidoctor //asciidoctor 를 의존하도록 하여, bootJar 생성 전에 asciidoctor task를 수행하도록 함
                     // (jar 파일 생성 시, 문서 생성을 보장 함)
   from("build/docs/asciidoc"){ //문서 생성 시, Jar 파일 내 static/docs 에도 복사되도록 함
      into 'BOOT-INF/classes/static/docs'
   }
}

...

!! 수정 내용 - build.gradle 파일 내

bootJar { ... from("build/docs/asciidoc") .... } 

-> bootJar { ... for("src/docs/asciidoc") ...} 변경해야 한다.

본 블로그에서 index.adoc 파일을 src/docs/asciidoc 하위에 생성했기 때문이다.

 

이번에 다시 restdocs 을 사용해야 해서 확인해봤는데... 잘못된 부분이 있네요....ㅎㅎ;;

 

 

 

gradle bootJar 실행 후, jar 파일 내부에 생성된 index.html 

 

 

5. 최종 화면 

bootJar 실행후, localhost:8080/docs/index.html 에 들어갔을 때 화면

 

 

전체 소스 코드 GitLab

https://gitlab.com/mskim0ct/spring-rest-docs-ex.git

 

mskim / Spring Rest Docs Ex

spring rest docs example

gitlab.com


 

영상, 블로그 따라하다가 발생한 문제

1. gradle 버전으로 인한 plugin 문제

gradle 버전이 4.9 이상이면, adoc을 변환하는 plugin은 org.asciidoctor.jvm.convert 이다.

org.asciidoctor.convert -> org.asciidoctor.jvm.convert

 

https://asciidoctor.github.io/asciidoctor-gradle-plugin/master/user-guide/

 

Asciidoctor Gradle Plugin Suite

This collection of plugins requires at least Gradle 4.9, JDK 8.0 and AsciidoctorJ 2.0.0 to run. If you need prior Gradle, JDK or AsciidoctorJ support please use a plugin from the 1.5.x or 1.6.x release series.

asciidoctor.github.io

 

 

2. "cannot locate a guava jar in the gradle distribution" 문제

해당 문제는 plugins에 추가한 org.asciidoctor.jvm.convert 버전 문제로 3.3.2 로 올리면 해결된다.

https://stackoverflow.com/questions/69637205/cannot-locate-a-guava-jar-in-the-gradle-distribution

 

Cannot locate a Guava Jar in the gradle distribution?

I have the following error while performing the command gradle build: What went wrong: Execution failed for task ':asciidoctor'. Cannot locate a Guava JAR in the Gradle distribution I couldn't f...

stackoverflow.com

 

3. 생성된 html 파일이 jar 파일 static/docs 내부에 생성되지 않는 문제

경로를 직접 입력하여 html 파일이 jar 파일 내 static/docs 내에 복사되도록 하였다.

[ 변경 전 ]
[ 변경 후 ]

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함