인프런 커뮤니티 질문&답변

류재준님의 프로필 이미지

작성한 질문수

실전! 스프링 부트와 JPA 활용2 - API 개발과 성능 최적화

회원 등록 API

junit으로 회원등록 API 테스트 코드를 만들어 보았습니다.

해결된 질문

21.01.09 17:35 작성

·

524

8

junit으로 회원 등록 API 테스트 코드를 만들어 보았습니다.

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
class MemberApiControllerTest {

@Autowired
MockMvc mockMvc;

@Autowired
ObjectMapper objectMapper;

// @BeforeEach
// void setUp(@Autowired MemberApiController memberApiController){
// mockMvc = MockMvcBuilders.standaloneSetup(memberApiController).build();
// }

@Test
@DisplayName("회원_등록API_V1")
void 회원_등록ApiV1() throws Exception {
//given
MemberDto memberDto = new MemberDto("회원1");

final String jsonStr = objectMapper.writeValueAsString(memberDto);

//when
final ResultActions resultActions = mockMvc.perform(post("/api/v1/members")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonStr)
).andDo(print());

//then
resultActions.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value("1"));
}

@Data
@AllArgsConstructor
static class MemberDto {
private String name;

}

@Test
@DisplayName("회원_등록API_V2")
void 회원_등록ApiV2() throws Exception {
//given
MemberDto memberDto = new MemberDto("회원2");

final String jsonStr = objectMapper.writeValueAsString(memberDto);

//when
final ResultActions resultActions = mockMvc.perform(post("/api/v2/members")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonStr)
).andDo(print());

//then
resultActions.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value("1"));
}


@Test
@DisplayName("회원정보_업데이트V2")
void 회원정보_업데이트V2() throws Exception {
//given
MemberDto memberDto = new MemberDto("회원3");

final String jsonStr = objectMapper.writeValueAsString(memberDto);
//when
final ResultActions resultActions = mockMvc.perform(post("/api/v2/members/1")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonStr)
).andDo(print());

//then
resultActions.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value("1"))
.andExpect(jsonPath("$.name").value("회원3"));
}

}

감사합니다.

답변 1

1

김영한님의 프로필 이미지
김영한
지식공유자

2021. 01. 09. 20:27

ㅎㅎ 다른분들에게도 도움이 되겠네요 고맙습니다^^