RestApi 만들기 - 이벤트 조회 API구현 (10)

반응형
반응형

곧 회사일이 바빠진다고 한다.
바빠지기 전에 열심히 공부 하자!

간단하게 테스트 부터 작성해보자.

@Test
  public void create_event() throws Exception {
    Delivery delivery = generateEvent(100);
    this.mockMvc.perform(get("/api/delivery/{id}",delivery.getId()))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("id").exists())
                .andExpect(jsonPath("_links.self").exists())
                .andExpect(jsonPath("_links.profile").exists());
  }

이것을 실행하면
어떤 에러가 발생할까?

왜 404가 발생할까?
왜냐하면...
controller에 만들지 않았기 때문이다.

그전에 만약에 잘못된 정보를 입력하게 되면 어떻게 될까?

@Test
  public void create_event_bad() throws Exception {
    this.mockMvc.perform(get("/api/delivery/9999999"))
        .andDo(print())
        .andExpect(status().isNotFound())
        .andExpect(jsonPath("id").exists())
        .andExpect(jsonPath("_links.self").exists())
        .andExpect(jsonPath("_links.profile").exists());
  }

그러면 이거는 성공할까?
사실..이것도 실패한다.

왜냐하면 리소스를 만들지 않았기 때문이다.
controller를 만들자.

@GetMapping("/{id}")
  public ResponseEntity<?> getEvent(@PathVariable Integer id) {
    Optional<Delivery> delivery = deliveryRepository.findById(id);
    if (delivery.isEmpty()) {
      return ResponseEntity.notFound().build();
    }
        
    return ResponseEntity.ok(delivery);
}

이렇게 작성하면 될까?
애석하게도 이건 정답이 아니다.
왜냐하면 리소스를 만들지 않았기 때문이다.

리소스를 만들자.

@GetMapping("/{id}")
  public ResponseEntity<?> getEvent(@PathVariable Integer id) {
    Optional<Delivery> optionalDelivery = deliveryRepository.findById(id);
    if (optionalDelivery.isEmpty()) {
      return ResponseEntity.notFound().build();
    }
    Delivery delivery = optionalDelivery.get();
    EntityModel<Delivery> deliveryModel = DeliveryModel.modelOf(delivery);
    return ResponseEntity.ok(deliveryModel);
  }

생각해보니 

public class DeliveryModel extends EntityModel<Delivery> {

  public static EntityModel<Delivery> modelOf(Delivery delivery) {
    EntityModel<Delivery> deliveryModel = EntityModel.of(delivery);
    deliveryModel.add(linkTo(DeliveryController.class).withRel("query-events"));
    deliveryModel.add(linkTo(DeliveryController.class).slash(delivery.getId()).withRel("update-events"));
    deliveryModel.add(linkTo(DeliveryController.class).slash(delivery.getId()).withSelfRel());
    return deliveryModel;
  }
}

이곳에서 profile은 빼줘야 된다.
왜냐하면 여기에 존재하는 링크들은 글로벌?링크이기 때문에...
빼주는게 맞는것 같다.
그러면 테스트가 많이 깨질것 같은디ㅜㅜ
아무튼
이것을 실행해보면

_links.profile이 존재하지 않는다고 나온다.
링크를 추가해주자.
이제 프로파일이 뭔지 알것 같다.

이렇게 추가하면 모든 예외처리는 마쳤다.

이제 docs를 만들어보자.
이 부분은 request부분은 url만 존재하구
나머지는 존재하지 않기 때문에 굳이 만들지 않아도 될것 같다.

@Test
  public void create_event() throws Exception {
    Delivery delivery = generateEvent(10);
    this.mockMvc.perform(get("/api/delivery/{id}", delivery.getId()))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(jsonPath("id").exists())
        .andExpect(jsonPath("_links.self").exists())
        .andExpect(jsonPath("_links.profile").exists())
        .andDo(document("get-event",
            links(linkWithRel("query-events").description("이벤트 생성"),
                linkWithRel("update-events").description("이벤트 수정"),
                linkWithRel("self").description("해당 이벤트로 이동"),
                linkWithRel("profile").description("해당 이벤트로 이동")),
            responseHeaders(headerWithName(HttpHeaders.CONTENT_TYPE).description("현재 contentType")),
            responseFields(fieldWithPath("id").description("현재 이벤트 아이디"),
                fieldWithPath("item").description("상품명"),
                fieldWithPath("user").description("판매자"),
                fieldWithPath("deliveryTime").description("출발 시간"),
                fieldWithPath("deliveryEndTime").description("도착 시간"),
                fieldWithPath("status").description("베송 상태"),
                fieldWithPath("itemPrice").description("물품 가격"),
                fieldWithPath("deliveryCost").description("배송가격"),
                fieldWithPath("_links.query-events.href").description("이벤트 링크로 가기"),
                fieldWithPath("_links.update-events.href").description("이벤트 수정 링크 이동"),
                fieldWithPath("_links.self.href").description("해당 링크로 이동하기"),
                fieldWithPath("_links.profile.href").description("이벤트 프로파일 링크이동하기"))));
  }

이거는 생각보다 어렵지 않았다.;;
완성품

반응형

댓글

Designed by JB FACTORY