Spring-boot
스프링부트에서 테스트 코드 작성하기-2
Oxix
2022. 7. 1. 15:22
롬복 사용해 보기
롬복 ?
롬복은 자바 개발할 때 자주 사용하는 Getter, Setter, 기본 생성자, toString 등을 어노테이션으로 자동 생성해준다.
import lombok.Getter; import lombok.RequiredArgsConstructor; @Getter @RequiredArgsConstructor public class HelloResponseDto { private final String name; private final int amount; }
- @Getter : 선언된 모든 필드의 get 메서드를 생성해 준다.
- @RequireArgsConstructor : 선언된 모든 final 필드가 포함된 생성자를 생성해 준다 , final이 없는 필드는 생성자에 포함되지 않는다.
해당 클래스의 테스트 코드는 다음과 같다.
import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class HelloResponseDtoTest { @Test public void funcTest() { String name = "test"; int amount = 1000; HelloResponseDto dto = new HelloResponseDto(name, amount); assertThat(dto.getName()).isEqualTo(name); assertThat(dto.getName()).isEqualTo(name); assertThat(dto.getAmount()).isEqualTo(amount); } }
assertThat
- assertj라는 테스트 검증 라이브러리의 검증 메서드이다.
- 검증하고 싶은 대상을 메서드 인자로 받는다.
- 메서드 체이닝이 지원되어 isEqualTo와 같이 메서드를 이어서 사용 가능하다.
테스트가 정상적으로 수행되는 것을 확인했으면 ResponseDto를 사용해볼 수 있다.
@Test public void printHelloDto() throws Exception { String name = "Hello"; int amount = 1000; mvc.perform( get("hello/dto") .param("name", name) .param("amount", String.valueOf(amount))) .andExpect(status().isOk()) .andExpect(jsonPath("$.name", is(name))) .andExpect(jsonPath("$.amount", is(amount))); }
param
- API 테스트할 때 사용될 요청 파라미터 설정
- 단, 값은 String형만 허용된다. -> 숫자/날짜 -> 문자열로 변경해야함.
jsonPath
- JSON 응답값을 필드별로 검증할 수 있는 메서드이다.
- $를 기준으로 필드명을 명시한다.
- 여기서는 name과 amount를 검증하니 $.name, $.amount로 검증한다.
배운 점
- TDD와 단위 테스트의 의미
- 스프링 부트 환경에서 테스트 코드 작성하는 법
- 롬복의 사용 방법