Spring/test

[Spring Rest Docs] Intellij + Kotlin DSL + Rest Docs 설정하기

MOMOBOB 2021. 12. 29. 01:27
반응형

Gradle 설정

  • build.gradle.kts
plugins {
	...(중략)...
    
	id("org.asciidoctor.jvm.convert") version "3.3.2"

	...(중략)...
}

dependencies {
	...(중략)...
    
	testImplementation("org.springframework.restdocs:spring-restdocs-asciidoctor")
	testImplementation("org.springframework.restdocs:spring-restdocs-mockmvc")
    
    ...(중략)...
}


tasks {
	val snippetsDir = file("$buildDir/generated-snippets")

	clean {
		delete("src/main/resources/static/docs")
	}

	test {
		useJUnitPlatform()
		systemProperty("org.springframework.restdocs.outputDir", snippetsDir)
		outputs.dir(snippetsDir)
	}

	build {
		dependsOn("copyDocument")
	}

	asciidoctor {
		dependsOn(test)

		attributes(
			mapOf("snippets" to snippetsDir)
		)
		inputs.dir(snippetsDir)

		doFirst {
			delete("src/main/resources/static/docs")
		}
	}

	register<Copy>("copyDocument") {
		dependsOn(asciidoctor)

		destinationDir = file(".")
		from(asciidoctor.get().outputDir) {
			into("src/main/resources/static/docs")
		}
	}

	bootJar {
		dependsOn(asciidoctor)

		from(asciidoctor.get().outputDir) {
			into("BOOT-INF/classes/static/docs")
		}
	}
}

 

예제 Spring Boot 테스트 코드

  • 테스트 예제 코드
@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureRestDocs(uriScheme = "https", uriHost = "localhost")
class DeveloperControllerTest(@Autowired var developerService: DeveloperService) {
    @Autowired
    private lateinit var mockMvc: MockMvc
    
    ...(중략)...
    
    @Test
    fun testFind() {

        mockMvc.perform(
            RestDocumentationRequestBuilders.get("$uri/{email}", findDeveloperEmail)
        )
            .andExpect(MockMvcResultMatchers.status().isOk)
            .andDo(MockMvcResultHandlers.print())
            .andDo(
                document(
                    "find-developer",
                    pathParameters(
                        parameterWithName("email").description("이메일")
                    ),
                    responseFields(
                        fieldWithPath("email").description("이메일"),
                        fieldWithPath("name").description("이름"),
                        fieldWithPath("introduction").description("소개"),
                        fieldWithPath("pictureUrl").description("사진경로"),
                        fieldWithPath("point").description("점수"),
                        fieldWithPath("popularity").description("인기도"),
                    )
                )
            )
    }
    
    ...(중략)...
}

 

반응형

 


이제 테스트 코드를 실행만 하면 build/generated-snippets에 test코드에 작성한 document의 identifier와 같은 디렉토리들이 생김.


이 폴더들 밑에 있는 것이 snippet이라고 하는 문서조각들이 자동으로 생성되는데 이것들을 이용하여 문서를 조합하면됨.

 

조합하는 방법은 src/docs/asciidoc 디렉토리 아래에 api-docs.adoc이라는 파일을 직접 만들어서 asciidoc라고하는 마크업언어를 이용하여 작성하면된다. (이름은 자유롭게하면 되나 추후 정적으로 접근할 html명이 됨)


그리고 AsciiDoc Plugin을 설치하면 asciidoc로 작성한 것을 미리볼 수 있으니 꼭 설치해보시길 바람.


asciidoc 사용법 참고 : https://narusas.github.io/2018/03/21/Asciidoc-basic.html

  • api-docs.adoc 예시
ifndef::snippets[]
:snippets: ../../../build/generated-snippets
endif::[]
= Application Name
:toc: left
:toclevels: 2
:sectlinks:

...(중략)...

[[resources-developer-find]]
=== 조회 API

==== HTTP request
include::{snippets}/find-developer/path-parameters.adoc[]
include::{snippets}/find-developer/http-request.adoc[]

==== HTTP response
include::{snippets}/find-developer/response-fields.adoc[]
include::{snippets}/find-developer/response-body.adoc[]
include::{snippets}/find-developer/http-response.adoc[]


adoc파일을 작성완료하고 build하면 resources/static/docs아래에 html파일이 생성됨.

 

그리고 어플리케이션에 http://localhost:8080/docs/api-docs.html로 접속하면 아래와 같이 html을 확인할 수 있다.

 

테스트 및 문서화 툴 찾다가 스웨거보다 좋은게 있다고 해서 써봤는데 UI는 별로지만 테스트기반 개발을 할 수 있어서 좋을 것 같음.
위에서 본대로 테스트가 성공하지 않으면 문서가 생기지 않고 문서를 만들기 위해선 테스트를 해야하도록 유도하기 때문에 테스트주도적인 개발하기에 좋을 듯?ㅎㅎ

내생각 REST docs의 최대장점 : API 문서의 신뢰도 100%!!

 

 


Thank you!

 

 

반응형