TIL 3 | 롬복 (Lombok)

softpeter·2021년 8월 18일
0
post-thumbnail

롬복

정의

  • Getter, Setter, 기본생성자, toString 등을 어노테이션으로 자동 생성해주는 라이브러리

프로젝트에 롬복 추가

build.gradle 에 코드 작성을 통해 프로젝트에 롬복을 추가

dependencies {
    implementation 'org.testng:testng:7.1.0'
    implementation 'org.testng:testng:7.1.0'
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.projectlombok:lombok')
    testCompile "org.projectlombok:lombok"
    annotationProcessor('org.projectlombok:lombok')
    testAnnotationProcessor('org.projectlombok:lombok')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}
  • org.projectlomok 추가

롬복으로 리팩토링

Hello Controller 코드를 롬복으로 전환하기

  • 롬복으로 변경하고 문제가 생기는지는 테스트 코드만 돌려서 확인

HelloResponseDto 클래스 생성

package scraping.coocon.com.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이 없는 필드는 생성자에 포함되지 않음

HelloResponseDtoTest 클래스 생성

package scraping.coocon.com.web.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와 같이 메소드를 이어서 사용 가능

  • isEqualTo
    : assertj의 동등 비교 메소드
    : assertThat에 있는 값과 isEqualTo의 값을 비교해서 같을때만 성공

HelloContorller에도 새로 만든 ResponseDto를 사용하도록 코드 추가

package scraping.coocon.com.web;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.
RestController;
import scraping.coocon.com.web.dto.HelloResponseDto;

@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);
    }
}
  • @RequestParam
    : 외부에서 API로 넘긴 파라미터를 가져오는 어노테이션

추가된 API를 테스트하는 코드를 HelloControllerTest에 추가

package scraping.coocon.com.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
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 응답값을 필드별로 검증할 수 있는 메소드
    : $를 기준으로 필드명을 명시
profile
dev.Back-end | Aal izz well

0개의 댓글