본문 바로가기
개발/Spring

[Spring] 스프링 부트에서 Spring Rest Docs 적용하기

by devhooney 2022. 11. 30.
728x90

Spring Rest Docs 적용하기

 

728x90

 

 

 

예전에 Swagger 사용법을 정리한 포스팅을 작성했었다.

[Spring] 스웨거(Swagger) 라이브러리

 

[Spring] 스웨거(Swagger) 라이브러리

기존에는 api 테스트를 위해서 포스트맨을 사용했는데, 스웨거는 서버로 요청되는 api 리스트를 html 화면으로 문서화해서 테스트할 수 있는 라이브러리이다. @RestController를 읽어서 api를 분석해서h

devhooney.tistory.com

강의를 들으면서 정리를 했던 것인데,

이번에도 강의를 들으면서 Spring Rest Docs를 내 프로젝트에 적용을 해봤다.

Swagger와 역할은 비슷하지만, 테스트 코드를 강제한다는 특징이 있다.

현업에서는 보통 두 개의 라이브러리를 혼용한다고 한다.

 

 

1. 라이브러리 설치

testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'

 

2. 테스트 코드 폴더 안에 RestDocsConfiguration 클래스 생성

- RestDocs에 관련된 설정을 할 수 있다.

- 아래 코드는 문서 내용을 보기 좋게 바꿔주는 코드이다.

@TestConfiguration
public class RestDocsConfiguration {

    @Bean
    public RestDocsMockMvcConfigurationCustomizer restDocsMockMvcConfigurationCustomizer() {
        return configurer -> configurer.operationPreprocessors()
                .withRequestDefaults(prettyPrint())
                .withResponseDefaults(prettyPrint());
    }

}

 

3. 코드 작성

- Entity 작성

package com.example.restapi.events;

import lombok.*;

import javax.persistence.*;
import java.time.LocalDateTime;

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Entity
public class Example {

    @Id
    @GeneratedValue
    private Integer id;
    private String name;

}

 

- DTO 작성

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class ExampleDto {

    @NotEmpty
    private String name;

}

 

 

- 요청, 응답 문서화

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureRestDocs
@Import(RestDocsConfiguration.class)
public class ExampleControllerTests {
    @Autowired
    MockMvc mockMvc;

    @Autowired
    ObjectMapper objectMapper;

    @Test
    @DisplayName("예시")
    public void helloExample() throws Exception {
        Example example = ExampleDto.builder()
                .name("Example")
                .build();

        mockMvc.perform(post("/api/example")
                    .contentType(MediaType.APPLICATION_JSON_VALUE)
                    .accept(MediaTypes.HAL_JSON)
                    .content(objectMapper.writeValueAsString(example)))
                .andDo(print())
                .andExpect(status().isCreated())
                .andExpect(jsonPath("name").exists())
                .andDo(document("create-example"));
        ;
    }
}

 

4. 테스트 실행

- 테스트를 실행하면 /build/generated-snippets/create-example 폴더가 생기고 안에 문서들이 작성된다.

- 요청 문서 내용

[source,options="nowrap"]
----
{
  "name" : "Example"
}
----

 

- 응답 문서 내용

[source,options="nowrap"]
----
{
  "id" : 1,
  "name" : "Example"
}
----

 

 

- 컨트롤러, 리포지토리 등 코드는 생략

 

 

여기까지 하면 snippet들이 생성되는데,

이 파일들 가지고 빌드하여 html파일로 만들어준다.

하지만 과정이 너무 번거로워서 Swagger를 쓰는게 편하게 느껴졌다.

 

 

 

- 참고

https://www.inflearn.com/course/spring_rest-api/unit/16429?category=questionDetail&q=38456&tab=curriculum

728x90