일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- map
- REST Docs
- 김영한
- IntelliJ
- 스프링 DB 2편
- Hashtable
- api 문서
- 단방향연결리스트
- spring boot
- whitelabel error page
- python
- jsp
- properties 한글깨짐
- properties ??
- java
- 인프런 #김영한
- 인프런 김영한
- 자바
- linkedlist
- MVC 2편
- 스프링MVC 1편
- Spring
- 404
- 백준
- 김영한 #DB1편
- Today
- Total
산업공학도의 IT
Spring Rest Docs 본문
ㅇAPI 문서를 만드는 이유
- Clinet 입장에서는 어떤 API가 있고, API의 사용방법을 모르기 때문이다
ㅇSpring RestDocs
- 운영중인 코드에 영향이 없다
- Test케이스를 토대로 문서를 자동 생성해준다
스프링 공식문서를 참고하여 그래들에 빌드해주자
그 후 API생성을 위한 DocTest클래스를 만들어주자
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith({RestDocumentationExtension.class,SpringExtension.class})
public class PostControllerDocTest {
}
공식문서는 위와 같이 나와있지만 나는 SpringBootTest 어노테이션을 사용할 것이기때문에 아래와 같이 해주었다.
(참고로 @SpringBootTest는 @ExtendWith(SpringExtension.class)를 가지고 있기때문에 가능하다.
package com.study.controller;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.restdocs.RestDocumentationExtension;
@SpringBootTest
@ExtendWith(RestDocumentationExtension.class)
public class PostControllerDocTest {
}
다음으로 MockMvc 초기화 코드를 작성해줍니다
원래 테스트코드 작성할 때 @AutoConfigureMockMvc 어노테이션을 사용하여 Mock을 주입받았었지만,
아래에서는 MockMvc를 직접 초기화 해주는 모습이다.(전 Junit5를 사용하였습니다)
@SpringBootTest
@ExtendWith(RestDocumentationExtension.class)
public class PostControllerDocTest {
private MockMvc mockMvc;
@BeforeEach
void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(restDocumentation))
.build();
}
}
다음으로 RESTful서비스 호출입니다
아래는 제가 만든 Get요청 컨트롤러이며, 아래를 바탕으로 API생성을 위한 테스트코드 작성입니다.
@GetMapping("/posts/{postid}")
public PostResponse get(@PathVariable Long postid) {
PostResponse post = postService.get(postid);
return post;
}
@Test
@DisplayName("글 단건 조회")
void test() throws Exception {
// given
// 글 제목과 내용을 위한 Post 클래스
Post requestpost = Post.builder()
.title("제목")
.content("내용")
.build();
// JPA를 사용하여 DB에 저장
postRepository.save(requestpost);
// expected
this.mockMvc.perform(get("/posts/{postId}",requestpost.getId())
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print()) //body에 어떤 값이 날라오는지 보기위해 넣음
.andExpect(status().isOk())
.andDo(document("index"));
}
테스트코드 실행을 하면 아래의 경로에 스니펫이 생성되며, 스니펫 사용을 위해 소스파일을 아래와 같이 생성해줍니다
저는 요청과 응답만 보고 싶어 아래와같이 작성 후 빌드해주었습니다.
빌드 후 build/docs/asciidoc에 생성된 index.html파일을 src/main/resources/static/docs에 복사 후 서버켜서 확인해보면
이와같이 문서가 잘 나온것을 확인할 수 있다.
마지막으로 이 문서를 커스터마이징이 가능하나 티스토리에 남기진 않겠습니다.
*참고
- 인프런 호돌맨
- 스프링 REST 문서