💐 Spring/Spring REST API

7) [test] @JUnitParams 테스트 코드 리팩토링 - 스프링 REST API

2020. 9. 12. 17:05
목차
  1. 테스트 클래스
  2. EventControllerTest.class
반응형

 

 

비즈니스 로직 적용 됐는지 응답 메시지 확인

  • offline 과 free 값 확인

비즈니스 로직

  • 일단 offline은 location에 값이 들어있으면 오프라인이고, 값이 없으면 온라인으로 진행이 된다.
  • free값은 basePrice와, MaxPrice가 둘 다 0일때 , free 이다.

Event.class

  • 도메인 클래스에다가 비즈니스 로직을 적용시켜준다.
    public void update() {
           this.free = (basePrice == 0) && (maxPrice == 0);
           this.offline = location != null;
       }

EventTests.class

@Test
public void testOffine() {

    // Given
    Event event = Event.builder()
                    .location("강남역")
                    .build();

    // When
    event.update();

    // Then
    assertThat(event.isOffline()).isEqualTo(true);



    // Given
    event = Event.builder()
                .build();

    // When
    event.update();

    // Then
    assertThat(event.isOffline()).isEqualTo(false);
}


@Test
public void testFree(){

    // Given
    Event event = Event.builder()
                    .basePrice(0)
                    .maxPrice(0)
                    .build();

    // When
    event.update();

    // Then
    assertThat(event.isFree()).isEqualTo(true);



    // Given
    Event event = Event.builder()
                    .basePrice(0)
                    .maxPrice(100)
                    .build();

    // When
    event.update();

    // Then
    assertThat(event.isFree()).isEqualTo(false);
}

 

만약 테스트 할 양이 무수히 많다면, 일일히 다 작성하는건 정말 귀찮을 것이다.
이럴때 사용할 수 있는 아주 좋은 애노테이션이 있다.

 

maven dependency 추가

 <!-- https://mvnrepository.com/artifact/pl.pragmatists/JUnitParams -->
         <dependency>
             <groupId>pl.pragmatists</groupId>
             <artifactId>JUnitParams</artifactId>
             <version>1.1.1</version>
             <scope>test</scope>
         </dependency>

적용법

     Junit5 에서는 이런식으로 작성해야한다.
     @ParameterizedTest
     @CsvSource({
             "0,0,true",
             "100, 0, false"
     })
     또는,
     @MethodSource("method Name")

테스트 클래스

@RunWith(JUnitParamsRunner.class)
 class EventTest {

         .
         . //코드 생략
         .


@ParameterizedTest
     @MethodSource("parametersForOffline")
     public void offline_인지_아닌지(String location, boolean offline) {

        // Given
        Event event = Event.builder()
                 .location(location)
                 .build();

         // When
         event.update();

         // Then
         assertThat(event.isOffline()).isEqualTo(offline);
     }

     private static Object[] parametersForOffline() {
         return new Object[] {
                 new Object[] {"korea", true},
                 new Object[] {null , false}
         };
     }

 @ParameterizedTest
     @MethodSource("parametersForTestFree")
     public void testFree(int basePrice, int maxPrice, boolean free) {

         // Given
         Event event = Event.builder()
                 .basePrice(basePrice)
                 .maxPrice(maxPrice)
                 .build();


        // When
        event.update();

        // Then
        assertThat(event.isFree()).isEqualTo(free);

     }


     // type-safe 하게 메소드로 빼놨다.
     private static Object[] parametersForTestFree() {
         return new Object[]{
                 new Object[] {0, 0, true},
                 new Object[] {100, 0, false},
                 new Object[] {0, 100, false}
         };
     }

 

EventControllerTest.class

 @Test
     @TestDescription("비즈니스 로직 적용 테스트")
     public void createEvent_logic() throws Exception {
         EventDto event = EventDto.builder()
                 .name("Spring")
                 .description("REST API Development with Spring")
                 .beginEnrollmentDateTime(LocalDateTime.of(2020, 9, 7, 2, 45))
                 .closeEnrollmentDateTime(LocalDateTime.of(2020, 9, 8, 2, 45))
                 .beginEventDateTime(LocalDateTime.of(2020, 9, 9, 2, 45))
                 .endEventDateTime(LocalDateTime.of(2020, 9, 10, 2, 45))
                 .basePrice(100)
                 .maxPrice(200)
                 .limitOfEnrollment(100)
                 .location("Daejoen")
                 .build();
         //Mock객체로 받았기 때문에 save도 안될것이고, NullpointerException이 발생할것이다.
         //그리하여 Mockito.when(eventRepository.save(event)).thenReturn(event);
         // eventRepository.save가 호출이 되면 -> 그다음 event를 리턴하라.
 //        Mockito.when(eventRepository.save(event)).thenReturn(event);

         mockMvc.perform(post("/api/events/")
                 .contentType(MediaType.APPLICATION_JSON)//본문 요청에 json을 담아서 보내고 있다고 알려줌.
                 .accept(MediaTypes.HAL_JSON)//HAL_JSON으로 받는다.
                 .content(objectMapper.writeValueAsString(event)))//요청 본문에 넣어준다. objectMapper로 event를 json으로 변환후
                 .andDo(print())//어떤 응답과 요청을 받았는지 확인가능.
                 .andExpect(status().isCreated())//201요청이 들어왔는지?
                 .andExpect(jsonPath("id").exists()) //json에 id가 있는지?
                 .andExpect(header().exists(HttpHeaders.LOCATION))//헤더에 Location이 있는지
                 .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaTypes.HAL_JSON_VALUE))//content-type에 "application/hal+json"가 나오는지?
                 .andExpect(jsonPath("free").value(false))
                 .andExpect(jsonPath("offline").value(true))
                 .andExpect(jsonPath("eventStatus").value(EventStatus.PUBLISHED.name()))
         ;

     }
반응형
저작자표시 (새창열림)
  1. 테스트 클래스
  2. EventControllerTest.class
'💐 Spring/Spring REST API' 카테고리의 다른 글
  • [HAEOAS] linkTo 메소드 exception 발생
  • 6) [test] Bad_Request 응답 본문 만들기 - 스프링 REST API
  • 5) [test] 입력값 제한하기 (비즈니스 로직으로 검사) - 스프링 REST API
  • 4) [test] 입력값 제한하기 (Bad_Request 발생) - 스프링 REST API
iseunghan
iseunghan
꾸준하게 열심히..
iseunghan
iseunghan

공지사항

  • 어제보다 나은 오늘이 되기 위해 🔥
  • 분류 전체보기 (262)
    • 💐 Spring (14)
      • 개념 및 이해 (2)
      • Spring 핵심 기술 (24)
      • Spring REST API (8)
      • Spring MVC, DB 접근 기술 (7)
      • Spring Security (23)
      • Spring in Action (1)
    • 🌻 JAVA (84)
      • 자바 ORM 표준 JPA 프로그래밍 (20)
      • 알고리즘, 자료구조 (13)
      • 디자인 패턴 (7)
      • 정리정리정리 (43)
      • JUnit (1)
    • 🔖 Snippets (3)
      • Javascript (3)
    • ⚙️ Devops (22)
      • ⛏ Git (11)
      • 🐳 Docker (6)
      • 🐧 Linux (3)
      • 🌈 Jenkins (1)
      • 📬 Kafka (1)
    • 💬 ETC.. (4)
      • 💻 macOS (2)
    • 🌧️ ORM (2)
      • JPA (2)
    • 🐍 Python (3)
    • 📚 Databases (15)
      • 오라클로 배우는 데이터베이스 개론과 실습(2판) (3)
      • RealMySQL 8.0 (8)
    • 🔥 Computer Science (5)
      • 📡 네트워크 (5)
    • 🏷️ 협업 (1)
    • 📜 코딩테스트 (38)
      • BAEKJOON\수학 1, 수학 2 (8)
      • BAEKJOON\재귀 (5)
      • BAEKJOON\브루트 포스 (3)
      • BAEKJOON\정렬 (1)
      • BAEKJOON\백트래킹 (5)
      • BAEKJOON\BFS, DFS (6)
      • BAEKJOON\이분탐색 (1)
      • BAEKJOON\다이나믹 프로그래밍 (9)
      • BAEKJOON\그리디 알고리즘 (0)
    • ✨ ISEUNGHAN (1)

인기 글

최근 글

전체
오늘
어제
반응형
hELLO · Designed By 정상우.
iseunghan
7) [test] @JUnitParams 테스트 코드 리팩토링 - 스프링 REST API
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.