티스토리 뷰

Spring

Spring - Validation

0307kjb 2022. 1. 21. 18:40

Validation은 특정한 조건을 만족하지 못하고 작업을 수행 시 잘못된 요청을 돌려주게 만드는 과정이다.

@RequestBody에 @Validated와 해당 엔티티의 필드 항목에 어노테이션을 달아 조건을 붙여준다.(핵심)

 

@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Restaurant {

    @Id
    @GeneratedValue
    private long id;

    @NotEmpty
    private String name;

    @NotEmpty
    private String address;

    @Transient
    private List<MenuItem> menuItems;
}


// 컨트롤러 //

@CrossOrigin
@RestController
public class RestaurantController {

    @Autowired
    private RestaurantService restaurantService;

    @GetMapping("/restaurants")
    public List<Restaurant> getRestaurants(){
        return restaurantService.getRestaurants();
    }

    @GetMapping("/restaurants/{id}")
    public Restaurant getRestaurant(@PathVariable("id") long id){
        return restaurantService.getRestaurant(id);
    }

    @PostMapping("/restaurants")
    public ResponseEntity<?> saveRestaurant(@Validated @RequestBody Restaurant resource) throws URISyntaxException {
        Restaurant restaurant = Restaurant.builder().name(resource.getName()).address(resource.getAddress()).build();
        restaurantService.save(restaurant);
        URI location = new URI("/restaurant/" + restaurant.getId());
        return ResponseEntity.created(location).body("{}");
    }

    @PatchMapping("/restaurants/{id}")
    public void patchRestaurant(@PathVariable("id") long id, @Validated @RequestBody Restaurant resource){
        restaurantService.patchRestaurant(id, resource.getName(), resource.getAddress());
    }

}


// 테스트 //

@ExtendWith(SpringExtension.class)
@WebMvcTest(RestaurantController.class)
class RestaurantControllerTests {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private RestaurantService restaurantService;

    @Test
    public void save() throws Exception {

        Restaurant restaurant = Restaurant.builder().name("JOKER HOUSE").address("Seoul").build();

        restaurantService.save(restaurant);

        mvc.perform(post("/restaurants").
                contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"JOKER HOUSE\", \"address\":\"seoul\"}"))
                .andExpect(status().isCreated())
                .andExpect((ResultMatcher) header().string("location", "/restaurant/"+restaurant.getId()))
                .andExpect(content().string(containsString("{}")));

        verify(restaurantService).save(restaurant);
    }

    @Test
    public void inValidSave() throws Exception {
        mvc.perform(post("/restaurants").
                contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"\", \"address\":\"\"}"))
                .andExpect(status().isBadRequest());
    }

    @Test
    public void patchRestaurant() throws Exception {

        mvc.perform(patch("/restaurants/1004")
                .contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"SOOL HOUSE\", \"address\":\"Busan\"}"))
                .andExpect(status().isOk());

        verify(restaurantService).patchRestaurant(1004L, "SOOL HOUSE", "Busan");
    }

    @Test
    public void invalidPatchRestaurant() throws Exception {

        mvc.perform(patch("/restaurants/1004")
                .contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"\", \"address\":\"\"}"))
                .andExpect(status().isBadRequest());

    }
}

 

 

 

 

 

 

 

'Spring' 카테고리의 다른 글

Java, Mybatis, Oracle 연동 코드  (0) 2022.05.29
Spring - <JSON> data patch  (0) 2022.01.22
Spring - Exception  (0) 2022.01.21
JPA 활용.  (0) 2022.01.21
Spring5 , Mockito 관련 간단 정리.  (0) 2022.01.13
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함