해결된 질문
작성
·
531
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"));
}
}
감사합니다.