일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- mustache
- 알고리즘 #코딩테스트 #프로그래머스 #C++ #vector #string
- 해싱
- 프로그래머스
- C++
- index.html
- TDD
- JPA autiding
- baekjoon
- DB
- spring
- testcode
- SpringSecurity
- Comparable
- Java
- Gradle
- springboot
- gitignore
- 알고리즘
- DynamicProgramming
- SpringBean
- 코딩테스트
- kotlin
- test case
- tdo
- API
- JPA
- SpringDataJPA
- SpringFramework
- rombok
- Today
- Total
천천히, 한결같이
[Spring] DTO와 롬복 만들고 적용하기 본문
이동욱 님의 스프링 부트와 AWS로 혼자 구현하는 웹 서비스책을 공부하며 정리한 내용입니다. 틀린 정보가 있을 수 있으니 주의하시고 댓글로 남겨주시길 바랍니다.
DTO란?
Data Transfer Object로, 계층간 데이터 이동을 위한 자바 Beans라고 이해하시면 됩니다.
package com.hwanld.book.springboot.web.dto;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public class HelloResponseDto {
private final String name;
private final int amount;
}
@Getter
: 선언된 모든 필드의 get 메소드를 생성해 줍니다.
@RequiredArgsConstructor
: 선언된 모든 final 필드가 포함된 생성자를 생성해 줍니다. 따라서 final이 없는 필드는 생성자를 생성하지 않습니다.
다음과 같이 해당 정보를 받을 필드 값을 저장하고, getter/setter 등을 포함한 클래스라고 생각하면 되는데, 일반적으로 DTO는 getter, setter, toString(), equals 외에 다른 로직을 갖고 있지 않습니다.
DTO에 적용한 롬복 테스트하기
위 코드에서 볼 수 있드시, DTO에 롬복을 적용해서 getter와 setter를 자동으로 생성해 주었습니다. 그러면 이러한 기능이 정상적으로 작동하는지를 확인할 수 있는 아래 테스트 코드를 추가합니다.
package com.hwanld.book.springboot.dto;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class HelloResponseDtoTest {
@Test
public void 롬복_기능_테스트() {
//given
String name = "test";
int amount = 1000;
//when
HelloResponseDto dto = new HelloResponseDto(name, amount);
//then
assertThat(dto.getName()).isEqualTo(name);
assertThat(dto.getAmount()).isEqualTo(amount);
}
}
assertThat
: assertj라는 테스트 검증 라이브러리의 검증 메소드입니다. 검증하고 싶은 대상을 메소드 인자로 받고, 메소드 체이닝이 지원되어 이어서 다른 메소드를 사용할 수 있습니다.
isEqualTo
: assertj의 비교 메소드입니다. assertThat에 있는 값과 isEqualTo의 값을 비교해서 같을 때만 성공입니다.
컨트롤러에서 롬복 사용하기
작성한 테스트 메소드를 실행해서 성공적인 결과를 얻었다면 dto에서 롬복이 정상적으로 작동하고 있다는 것을 알 수 있기에 컨트롤러도 dto를 사용하는 형태로 코드를 추가합니다.
package com.hwanld.book.springboot.web;
import com.hwanld.book.springboot.dto.HelloResponseDto;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
@GetMapping("/hello/dto")
public HelloResponseDto helloDto(@RequestParam("name") String name, @RequestParam("amount") int amount) {
return new HelloResponseDto(name, amount);
}
}
이어서, 위 메소드를 검증하기 위해서 테스트 코드도 추가적으로 작성해줍니다.
package com.hwanld.book.springboot.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HelloController.class)
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void hello가_리턴된다() throws Exception {
String hello = "hello";
mvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string(hello));
}
@Test
public void helloDto가_리턴된다() 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 응답값을 필드별로 검증할 수 있는 메소드입니다. $를 기준으로 필드명을 명시합니다.
'Spring' 카테고리의 다른 글
[Spring] API 생성하기(1) (0) | 2021.12.29 |
---|---|
[Spring] 프로젝트에 Spring Data JPA 적용하고 테스트 코드 작성하기 (0) | 2021.12.27 |
[Spring] 컨트롤러 생성하고 테스트 코드로 검증하기 (0) | 2021.12.25 |
[Spring] TDD, 테스트 케이스란? (0) | 2021.12.23 |
[Spring] Gradle 프로젝트를 SpringBoot 프로젝트로 변경하기 (0) | 2021.12.23 |