[스프링부트와 AWS로 혼자 구현하는 웹서비스] 따라하기 CHAPTER 2_HelloController와 테스트코드

하도야지·2021년 6월 11일
post-thumbnail

1. 메인 클레스

package com.hadoyaji.book.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;


@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
  • @SpringBootApplication
    : 스프링부트의 자동설정, 스프링 Bean 읽기, 생성 자동 설정 처리함
    : 해당 @선언 위치부터 설정읽기 때문에 프로젝트 최상단에 선언

  • SpringApplication.run(Application.class,args);
    : 내장was 실행



2. Hello Controller와 테스트 코드

1) HelloController

package com.hadoyaji.book.springboot.web;

import com.hadoyaji.book.springboot.web.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);

    }
}
  • @RestController
    : 컨트롤러를 JSON 반환 컨트롤러로 만들어 줌
    : ASIS 각 메소드마다 @ResponseBody 선언해 주던 것과 같음

  • @GetMapping
    : HTTP Method get 요청 받을 수 있는 api 생성
    : ASIS @RequestMapping(method = RequestMethod.GET)와 같음


2) HelloControllerTest

import com.hadoyaji.book.springboot.config.auth.SecurityConfig;
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.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.security.test.context.support.WithMockUser;
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.*;

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HelloController.class,
            excludeFilters = {
            @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class)
            })
public class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

    @WithMockUser(roles="USER")
    @Test
    public void hello_가_리턴된다() throws Exception{
            String hello = "hello";

            mvc.perform(get("/hello"))
                    .andExpect(status().isOk())
                    .andExpect(content().string(hello));
    }

    @WithMockUser(roles = "USER")
    @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)));
    }

}
  • @RunWith(SpringRunner.class)
    :테스트 진행 시 JUNIT 내장 실행자 외 다른 실행자를 실행(SpringRunner)

  • @WebMvcTest
    : WEB(Spring MVC)에 집중할 수 있는 어노테이션
    : 선언 시 @Controller, @ControllerAdvice 등 사용 가능
    : @Service, @Component, @Repository는 사용 불가

  • @Autowired
    : 스프링이 관리하는 빈을 주입 받음

  • private MockMvc mvc;
    : 웹API 테스트 시 사용, 스프링MVC테스트의 시작점

  • mvc.perform(get("/hello"))
    : HTTP GET 요청

  • .andExpect(status().isOk())
    : 결과 검증


3. lombok 적용한 HelloResponseDto와 테스트 코드

1) HelloResponseDto

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class HelloResponseDto {

    private final String name;
    private final int amount;
}
  • *lombok 사용
  • @Getter : 선언한 필트에 get메소드 생성
  • @RequiredArgsConstructor
    : 선언된 모든 final필드가 포함된 생성자 생성 (final 미포함 시 생성 x)

2)HelloResponseDtoTest
: RequiredArgsConstructor로 생성자 생성 되는지 테스트

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);
    }
}
  • //given
    : 테스트할 데이터 값 세팅
  • //when
    : 테스트할 내용/상황 세팅
  • // then
    : 테스트할 기대값 검증
    assertThat : 검증하고 싶은 대상 메소드 인자 세팅
    isEqualTo : 동등비교 메소드
profile
프로그래머를 꿈꾸는 코더

0개의 댓글