기본 콘텐츠로 건너뛰기

냉장고 가계부 프로젝트 9

HATEOAS 적용을 일관성있게 하기위해서 FoodController 메서드 중 새로운 식품을 등록하는 메서드인 postFood 메서드도 리턴유형을 ResponseEntity<Food> 에서 ResponseEntity<FoodResource> 로 수정한다.
우선 테스트 메서드 postSave 부터 수정한다.
    @Test
    public void postSave() throws Exception {
        given(jpaFoodService.save(any(Food.class))).willReturn(milk);
        final ResultActions result = mvc.perform(post("/foods")
                .content(mapper.writeValueAsString(milk))
                .contentType(MediaType.APPLICATION_JSON_UTF8));
        result.andExpect(status().isCreated())
            .andExpect(redirectedUrlPattern("**/foods/{id:\\d+}"));
        verifyResultContent(result);
    }

변경된 부분은 mvc.perform 메서드를 ResultActions 형의 result 변수에 할당하고있다. 할당한 변수를 내부검증 메서드인 verfiyResultContent 메서드에 파라미터로 전달하고 있다.

다음은 FoodController 의 postFood 메서드이다.
    @PostMapping
    public ResponseEntity<FoodResource> postFood(@RequestBody final Food food) {
        jpaFoodService.save(food);
        URI location = MvcUriComponentsBuilder.fromController(getClass())
                .path("/{id}")    
                .buildAndExpand(food.getId())
                .toUri();
        return ResponseEntity.created(location).body(assembler.toResource(food));
    }

리턴문에서 body 파라미터로 assembler를 통해 food객체를 FoodResource 객체로 변환해주는 작업이 수정되었다.

이전글: 냉장고 가계부 프로젝트 8
다음글: 냉장고 가계부 프로젝트 10