토리맘의 한글라이즈 프로젝트 logo 토리맘의 한글라이즈 프로젝트

스프링 REST Docs 공식 레퍼런스를 한글로 번역한 문서입니다.

전체 목차는 여기에 있습니다.

목차


전송한 요청이나 받은 응답과는 완벽하게 일치하지 않는 문서를 작성하고 싶을 수도 있다. 스프링 Rest Docs는 문서 작성 전에 요청과 응답을 수정할 수 있는 여러 가지 전처리기를 제공한다.

전처리는 OperationRequestPreprocessor 또는 OperationResponsePreprocessor와 함께 document를 호출해 설정한다. Preprocessors에 있는 스태틱 메소드 preprocessRequest, preprocessResponse로 인스턴스를 가져올 수 있다. 다음은 그 방법을 보여준다:

MockMvc WebTestClient REST Assured
this.mockMvc.perform(get("/")).andExpect(status().isOk())
	.andDo(document("index", preprocessRequest(removeHeaders("Foo")), // (1)
			preprocessResponse(prettyPrint()))); // (2)
this.webTestClient.get().uri("/").exchange().expectStatus().isOk().expectBody()
	.consumeWith(document("index",
		preprocessRequest(removeHeaders("Foo")), // (1)
		preprocessResponse(prettyPrint()))); // (2)
RestAssured.given(this.spec)
	.filter(document("index", preprocessRequest(removeHeaders("Foo")), // (1)
			preprocessResponse(prettyPrint()))) // (2)
.when().get("/")
.then().assertThat().statusCode(is(200));

(1) Foo 헤더를 제거하는 요청 전처리기를 적용한다.
(2) 컨텐츠를 보기 좋게 출력해주는(pretty print) 응답 전처리기를 적용한다.

모든 테스트에 같은 전처리기를 적용하고 싶을 수도 있다. 이럴 땐 @Before 메소드에서 RestDocumentationConfigurer API를 사용해 전처리기를 설정하면 된다. 예를 들어 모든 요청에서 Foo 헤더를 제거하고 모든 요청을 보기 좋게 출력하고(pretty print) 싶다면, 다음 방법을 사용해라 (각자의 테스트 환경에 맞게):

MockMvc WebTestClient REST Assured
private MockMvc mockMvc;

@Before
public void setup() {
	this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
		.apply(documentationConfiguration(this.restDocumentation).operationPreprocessors()
			.withRequestDefaults(removeHeaders("Foo")) // (1)
			.withResponseDefaults(prettyPrint())) // (2)
		.build();
}
private WebTestClient webTestClient;

@Before
public void setup() {
	this.webTestClient = WebTestClient.bindToApplicationContext(this.context)
		.configureClient()
		.filter(documentationConfiguration(this.restDocumentation)
			.operationPreprocessors()
				.withRequestDefaults(removeHeaders("Foo")) // (1)
				.withResponseDefaults(prettyPrint())) // (2)
		.build();
}
private RequestSpecification spec;

@Before
public void setup() {
	this.spec = new RequestSpecBuilder()
		.addFilter(documentationConfiguration(this.restDocumentation).operationPreprocessors()
			.withRequestDefaults(removeHeaders("Foo")) // (1)
			.withResponseDefaults(prettyPrint())) // (2)
		.build();
}

(1) Foo 헤더를 제거하는 요청 전처리기를 적용한다.
(2) 컨텐츠를 보기 좋게 출력해주는(pretty print) 응답 전처리기를 적용한다.

그 다음 각 테스트에 필요한 설정을 적용하면 된다. 적용 방법은 다음 예제를 참고해라:

MockMvc WebTestClient REST Assured
this.mockMvc.perform(get("/"))
		.andExpect(status().isOk())
		.andDo(document("index",
				links(linkWithRel("self").description("Canonical self link"))
		));
this.webTestClient.get().uri("/").exchange().expectStatus().isOk()
	.expectBody().consumeWith(document("index",
		links(linkWithRel("self").description("Canonical self link"))));
RestAssured.given(this.spec)
	.filter(document("index",
		links(linkWithRel("self").description("Canonical self link"))))
	.when().get("/")
	.then().assertThat().statusCode(is(200));

위에서 보여준 전처리기 외에도 Preprocessors에 있는 스태틱 메소드를 통해 다양한 전처리기를 사용할 수 있다. 더 자세한 내용은 아래를 참고해라.


4.1. Preprocessors

4.1.1. Pretty Printing

Preprocessors에 있는 prettyPrint는 요청, 응답 컨텐츠 형식을 읽기 쉽게 바꿔준다.

하이퍼미디어 기반 API 문서를 작성한다면 하드 코딩한 URI 대신, 클라이언트가 링크를 통해 API를 탐색하도록 유도하고 싶을 수 있다. 한 가지 방법은 문서 내에 URI를 사용을 제한하는 것이다. PreprocessorsmaskLinks는 응답에 있는 모든 링크의 href로 바꾼다. 원한다면 대체할 문자열을 지정할 수도 있다.

4.1.3 Removing Headers

PreprocessorsremoveHeaders는 요청, 응답에서 전달 받은 헤더명과 일치하는 모든 헤더를 제거한다.

PreprocessorsremoveMatchingHeaders는 요청, 응답에서 전달 받은 정규식 패턴과 일치하는 모든 헤더를 제거한다.

4.1.4. Replacing Patterns

PreprocessorsreplacePattern은 요청, 응답 컨텐츠를 대체할 수 있는 범용 메커니즘을 제공한다. 정규식과 일치하는 모든 항목을 대체해버린다.

4.1.5. Modifying Request Parameters

PreprocessorsmodifyParameters로는 요청 파라미터를 추가, 설정, 제거할 수 있다.

4.1.6. Modifying URIs

서버에 바운드되지 않은 MockMvc나 WebTestClient를 사용한다면 이 설정을 바꿔서 URI를 커스텀해야 한다.

PreprocessorsmodifyUris로는 요청, 응답의 모든 URI를 수정할 수 있다. 서버에 바운드된 REST Assured나 WebTestClient를 사용한다면, 서비스 로컬 인스턴스를 테스트하면서 문서에 보이는 URI만 따로 커스텀할 수도 있다.

4.1.7. Writing Your Own Preprocessor

내장 전처리기로 해결할 수 없는 요구사항이 있다면 OperationPreprocessor 인터페이스를 직접 구현하면 된다. 커스텀 전처리기 사용법도 다른 내장 전처리기와 동일하다.

요청이나 응답 컨텐츠(바디)만 수정하고 싶다면, ContentModifier 인터페이스를 구현해서 내장 ContentModifyingOperationPreprocessor와 함께 쓰는 걸 고려해봐라.


Next :
Configuration
스프링 REST Docs 설정하기 한글 번역

전체 목차는 여기에 있습니다.

<< >>

TOP