반응형
오늘은 32강 Exception Handling 을 마무리하고
33강 Parameter Validator 강의를 들어보았다.
*HelloWorldController.java
package com.fastcampus.javaallinone.project3.mycontact.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@GetMapping(value = "/api/helloWorld")
public String helloWorld(){
return "HelloWorld";
}
@GetMapping(value = "api/helloException")
public String helloException(){
throw new RuntimeException("Hello RuntimeException");
}
}
*PersonController.java
package com.fastcampus.javaallinone.project3.mycontact.controller;
import com.fastcampus.javaallinone.project3.mycontact.controller.dto.PersonDto;
import com.fastcampus.javaallinone.project3.mycontact.domain.Person;
import com.fastcampus.javaallinone.project3.mycontact.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RequestMapping(value = "/api/person")
@RestController
@Slf4j
public class PersonController {
@Autowired
private PersonService personService;
@GetMapping("/{id}")
public Person getPerson(@PathVariable Long id){
return personService.getPerson(id);
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void postPerson(@RequestBody @Valid PersonDto personDto) {
personService.put(personDto);
}
@PutMapping("/{id}")
public void modifyPerson(@PathVariable Long id, @RequestBody PersonDto personDto){
personService.modify(id, personDto);
}
@PatchMapping("/{id}")
public void modifyPerson(@PathVariable Long id, String name){
personService.modify(id, name);
}
@DeleteMapping("/{id}")
public void deletePerson(@PathVariable Long id){
personService.delete(id);
}
}
*PersonDTO
package com.fastcampus.javaallinone.project3.mycontact.controller.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
import java.time.LocalDate;
@Data
@NoArgsConstructor
@AllArgsConstructor(staticName = "of")
public class PersonDto {
@NotBlank(message = "이름은 필수값입니다")
private String name;
private String hobby;
private String address;
private LocalDate birthday;
private String job;
private String phoneNumber;
}
*HelloWorldControllerTest
package com.fastcampus.javaallinone.project3.mycontact.controller;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
class HelloWorldControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@BeforeEach
void beforeEach(){
mockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.alwaysDo(print())
.build();
}
@Test
void helloWorld() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.get("/api/helloWorld")// http의 GET메서드로 /api/helloWorld를 호출
).andDo(print())//결과값을 보여주는 것
//아래는 자동화된 결과체크
.andExpect(status().isOk())//status가 200(Ok)인지 확인
.andExpect(MockMvcResultMatchers.content().string("HelloWorld"));
//respond의 내용이 body = HelloWorld인지 체크
}
@Test
void helloException() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/api/helloException"))
.andExpect(jsonPath("$.code").value(500))
.andExpect(jsonPath("$.message").value("알 수 없는 서버 오류가 발생하였습니다."));
}
}
*PersonControllerTest
package com.fastcampus.javaallinone.project3.mycontact.controller;
import com.fastcampus.javaallinone.project3.mycontact.controller.dto.PersonDto;
import com.fastcampus.javaallinone.project3.mycontact.domain.Person;
import com.fastcampus.javaallinone.project3.mycontact.domain.dto.Birthday;
import com.fastcampus.javaallinone.project3.mycontact.repository.PersonRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import javax.transaction.Transactional;
import java.time.LocalDate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@Slf4j
@SpringBootTest
@Transactional
class PersonControllerTest {
@Autowired
private PersonRepository personRepository;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
//BeforeEach를 달면 매 테스트마다 한번씩 실행이 됨
@BeforeEach
void beforeEach(){
mockMvc = MockMvcBuilders
.webAppContextSetup(wac)
.alwaysDo(print())
.build();
}
@Test
void getPerson() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.get("/api/person/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("martin"))
.andExpect(jsonPath("$.hobby").isEmpty())
.andExpect(jsonPath("$.address").isEmpty())
.andExpect(jsonPath("$.birthday").value("1991-08-15"))
.andExpect(jsonPath("$.job").isEmpty())
.andExpect(jsonPath("$.phoneNumber").isEmpty())
.andExpect(jsonPath("$.deleted").value(false))
.andExpect(jsonPath("$.age").exists()) //숫자를 넣을 경우 연도가 바뀜에 따라 테스트가 실패할 수 있어서 존재여부만 확인함
.andExpect(jsonPath("$.birthdayToday").isBoolean());
}
@Test
void postPerson() throws Exception{
PersonDto dto = PersonDto.of("martin", "programming", "판교", LocalDate.now(), "programmer", "010-1111-2222");
mockMvc.perform(
MockMvcRequestBuilders.post("/api/person")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(toJsonString(dto)))
.andExpect(status().isCreated());
Person result = personRepository.findAll(Sort.by(Sort.Direction.DESC, "id")).get(0);
assertAll(
() -> assertThat(result.getName()).isEqualTo("martin"),
() -> assertThat(result.getHobby()).isEqualTo("programming"),
() -> assertThat(result.getAddress()).isEqualTo("판교"),
() -> assertThat(result.getBirthday()).isEqualTo(Birthday.of(LocalDate.now())),
() -> assertThat(result.getJob()).isEqualTo("programmer"),
() -> assertThat(result.getPhoneNumber()).isEqualTo("010-1111-2222")
);
}
@Test
void postPersonIfNameIsNull() throws Exception {
PersonDto dto = new PersonDto();
mockMvc.perform(
MockMvcRequestBuilders.post("/api/person")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(toJsonString(dto)))
.andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.message").value("이름은 필수값입니다"));
}
@Test
void postPersonIfNameIsEmpty() throws Exception{
PersonDto dto = new PersonDto();
dto.setName("");
mockMvc.perform(
MockMvcRequestBuilders.post("/api/person")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.contentType(toJsonString(dto)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.message").value("이름은 필수값입니다"));
}
@Test
void postPersonIfNameIsBlankString() throws Exception {
PersonDto dto = new PersonDto();
dto.setName(" ");
mockMvc.perform(
MockMvcRequestBuilders.post("/api/person")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(toJsonString(dto)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.message").value("이름은 필수값입니다"));
}
@Test
void modifyPerson() throws Exception{
PersonDto dto = PersonDto.of("martin", "programming", "판교", LocalDate.now(), "programmer", "010-1111-2222");
mockMvc.perform(
MockMvcRequestBuilders.put("/api/person/1")
.contentType(MediaType.APPLICATION_JSON_VALUE)
//수정하지 않는 항목도 들어있어야 결과값이 null로 바뀌지 않음
.content(toJsonString(dto)))
.andExpect(status().isOk());
Person result = personRepository.findById(1L).get();
assertAll(
() -> assertThat(result.getName()).isEqualTo("martin"),
() -> assertThat(result.getHobby()).isEqualTo("programming"),
() -> assertThat(result.getAddress()).isEqualTo("판교"),
() -> assertThat(result.getBirthday()).isEqualTo(Birthday.of(LocalDate.now())),
() -> assertThat(result.getJob()).isEqualTo("programmer"),
() -> assertThat(result.getPhoneNumber()).isEqualTo("010-1111-2222")
);
}
@Test
void modifyPersonIfNameIsDifferent() throws Exception{
PersonDto dto = PersonDto.of("james", "programming", "판교", LocalDate.now(), "programmer", "010-1111-2222");
mockMvc.perform(
MockMvcRequestBuilders.put("/api/person/1")
.contentType(MediaType.APPLICATION_JSON_VALUE)
//수정하지 않는 항목도 들어있어야 결과값이 null로 바뀌지 않음
.content(toJsonString(dto)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.message").value("이름 변경이 허용되지 않습니다."));
}
@Test
void modifyPersonIfPersonNotFound() throws Exception {
PersonDto dto = PersonDto.of("martin", "programming", "판교", LocalDate.now(), "programmer", "010-1111-2222");
mockMvc.perform(
MockMvcRequestBuilders.put("/api/person/10")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(toJsonString(dto)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.message").value("Person Entity가 존재하지 않습니다."));
}
@Test
void modifyName() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.patch("/api/person/1")
.param("name","martinModified"))
.andExpect(status().isOk());
assertThat(personRepository.findById(1L).get().getName()).isEqualTo("martinModified");
}
@Test
void deletePerson() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.delete("/api/person/1"))
.andExpect(status().isOk());
assertTrue(personRepository.findPeopleDeleted().stream().anyMatch(person -> person.getId().equals(1L)));
}
private String toJsonString(PersonDto personDto) throws JsonProcessingException {
return objectMapper.writeValueAsString(personDto);
}
}
패스트캠퍼스 강의: https://bit.ly/3ilMbIO
Java 웹 개발 마스터 올인원 패키지 Online. | 패스트캠퍼스
자바 기초문법부터 프로젝트 실습까지 Java 문법부터 스프링/스프링부트, 트렌디한 기술인 JPA까지 모두 배우는 온라인 강의입니다.
www.fastcampus.co.kr
반응형
'언어공부 > JAVA&SPRING' 카테고리의 다른 글
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 42회차 미션 (0) | 2020.09.20 |
---|---|
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 41회차 미션 (0) | 2020.09.19 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 39회차 미션 (0) | 2020.09.17 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 38회차 미션 (0) | 2020.09.16 |
[패스트캠퍼스 수강 후기] 자바 인강 100% 환급 챌린지 37회차 미션 (0) | 2020.09.15 |
댓글