Hello Controller 테스트 코드 작성하기

1. 패키지 생성

  • [src > main > java] 에 패키지 생성
  • 패키지명은 웹 사이트 주소의 역순으로 생성이 일반적
  • ex) com.choee.service.springboot

2. 패키지 내에 Java 클래스 생성

package com.choee.service.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication 
public class Application { // 메인 클래스
    public static void main(String[] args) {SpringApplication.run(Application.class,args);} // SpringApplication.run : 내장 WAS 실행
}

@SpringBootApplication

  • 스프링 부트의 자동 설정
  • 스프링 Bean 읽기와 생성 모두 자동 설정,
  • @SpringBootApplication이 있는 위치부터 설정을 읽어가므로 메인 클래스틑 항상 프로젝트의 최상단에 위치해야한다.

Spring Bean 이란?

  • Spring에 의하여 생성되고 관리되는 자바 객체를 Bean이라고 한다.
  • 참조: melonicedlatte.com/2021/07/11/232800.html

내장 WAS(Web Application Server)란?

  • 별도로 외부에 WAS를 두지 않고 애플리케이션을 실행할 때 내부에서 WAS를 실행하는 것

내장 WAS 이용의 장점

  • 항상 서버에 톰캣을 설치할 필요가 없게 되고, 스프링 부트로 만들어진 Jar 파일(실행 가능한 java 패키징 파일)로 실행하면 된다.
  • 언제 어디서나 같은 환경에서 스프링 부트를 배포할 수 있다.

3. 현재 패키지 하위에 web 패키지 생성

  • 컨트롤러와 관련된 클래스들을 관리하는 패키지

HelloControler 클래스 생성하여 테스트 API 작성

package com.choee.service.springboot.web;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}

@RestController

  • 컨트롤러를 JSON을 반환하는 컨트롤러로 만들어준다.
  • 이전의 @ResponseBody를 각메소드마다 선언했던 것을 한번에 사용할 수 있게해주는 어노테이션

@GetMapping

  • HTTP Method인 Get의 요청을 받을 수 있는 API를 만들어 준다.
  • 이전엔 @RequestMapping(method = RequestMethod.GET)으로 사용

4. 테스트 코드로 검증

package com.choee.service.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 org.springframework.test.web.servlet.ResultActions;
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.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));
    }
}

@RunWith(SpringRunner.class)

  • 테스트를 진행할 때 Junit에 내장된 실행자 외에 다른 실행자를 실행시킨다.
  • SpringRunner라는 스프링 실행자 사용
  • 스프링 부트와 테스트 JUnit 사이의 연결자 역할을 한다.

@WebMvcTest

  • 여러 스프링 테스트 어노테이션 중, Web(Spring MVC)에 집중할 수 잇는 어노테이션
  • 선언할 경우 @Controller, @ControllerAdvice 등 사용 가능
  • @Service, @Component, @Repository 등 사용 불가

@Autowired

  • 스프링이 관리하는 Bean을 주입 받는다.

private MockMvc mvc

  • 웹 API를 테스트할 때 사용
  • 스프링 MVC 테스트의 시작점
  • 이 클래스를 통해 HTTP GET, POST 등에 대한 테스트를 할 수 있다

mvc.perform(get("/hello"))

  • MockMvc를 통해 /hello 주소로 HTTP GET 요청을 한다.
  • 체이닝일 지원되어(.and) 여러 검증 기능을 이어서 선언할 수 있다.

.andExpect(status().isOk())

  • mvc.perform의 결과를 검증한다
  • HTTP Header의 Status(200,404,500 등)를 검증한다.

.andExpect(content().string(hello))

  • mvc.perform의 결과를 검증한다.
  • 응답 본문의 내용을 검증한다.
  • Controller에서 리턴하는 값이 맞는지 검증

5. 테스트 코드 실행하여 확인

  • 메소드 왼쪽의 화살표 클릭
  • Run 'hello가_리턴된다()' 클릭

+ Recent posts