https://github.com/knight76/springboot2-restdocs  참고


Spring Rest Docs 및 Junit Test를 진행할 때 아래와 같이 부모 테스트 클래스를 둔 후, 자식 테스트에서 로직만 테스트하게 했더니 좀 편했다.


부모 테스트 클래스 

package com.example.controller;

import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.*;

import org.junit.Before;
import org.junit.Rule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.restdocs.JUnitRestDocumentation;
import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

public class ParentTest {

@Rule
public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();

@Autowired
WebApplicationContext context;

RestDocumentationResultHandler document;

MockMvc mockMvc;

@Before
public void setUp() {
this.document = document(
"{class-name}/{method-name}",
preprocessResponse(prettyPrint())
);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(documentationConfiguration( this.restDocumentation))
.alwaysDo(document)
.build();
}
}





자식 테스트 클래스 

package com.example.controller;

import static org.hamcrest.CoreMatchers.*;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*;
import static org.springframework.restdocs.payload.PayloadDocumentation.*;
import static org.springframework.restdocs.request.RequestDocumentation.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.ResultActions;

@RunWith(SpringRunner.class)
@AutoConfigureRestDocs
@SpringBootTest
public class HelloWorldTest extends ParentTest {

@Test
public void helloWorldJson() throws Exception {
// given
String response = "{\"result\":\"Welcome, Hello World, Samuel\"}";

// when
ResultActions result =
mockMvc.perform(get("/helloworld/json")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.param("name", "Samuel"))
.andDo(print());

// then
result.andExpect(status().isOk())
.andDo(document.document(
requestParameters(
parameterWithName("name").description("이름입니다.")),
responseFields(
fieldWithPath("result").description("결과입니다."))))
.andExpect(jsonPath("result", is(notNullValue())))
.andExpect(content().string(response));
}
}


Posted by '김용환'
,