인프런 영문 브랜드 로고
인프런 영문 브랜드 로고

Inflearn Community Q&A

nateen72481907's profile image
nateen72481907

asked

Real-world! Spring Boot and JPA Utilization 2 - API Development and Performance Optimization

Membership Registration API

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

Resolved

Written on

·

557

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"));
}

}

감사합니다.

springjavaJPAspring-boot

Answer 1

1

yh님의 프로필 이미지
yh
Instructor

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

nateen72481907's profile image
nateen72481907

asked

Ask a question