Spring Boot - 1

2020. 1. 11. 02:46학부 프로젝트/Temporage

@SpringBootApplication 은 스프링 부트의 자동 설정, 스프링 Bean 읽기와 생성을 모두 자동으로 설정한다. 또한 해당 annotation이 있는 위치부터 설정을 읽어가기 때문에 해당 어노테이션이 붙어있는 클래스는 프로젝트의 최상단에 항상위치 해야한다.

@SpringBootApplication
public class Application{
	public static void main(String[] args){
    	//SpringApplication.run으로 내장 WAS를 실행
    	SpringApplication.run(Application.class, args);
    }
}

 

 

@RestController은 컨트롤러를 JSON을 반환하는 컨트롤러로 만들어 준다. 이전에 @ReqquestBody를 메서드마다 붙였던걸 일괄적으로 적용시켜준다고 보면 된다.

 

@GetMapping은 Get request를 받을수 있는 API를 만들어준다. 이전에는 @RequestMapping(method = RequestMethod.GET)으로 사용되었다.

 


 

  • 테스트 코드
    • JUnit을 이용해 테스트 코드를 작성하려는 도중, @RunWith 어노테이션을 찾지못하는 에러가 발생.

  • gradle에 JUnit 4.12 버전을 추가해 주어서 해결함. 
  • gradle 코드는  https://mvnrepository.com 에서  검색해서 찾음

 

// https://mvnrepository.com/artifact/junit/junit
testCompile group: 'junit', name: 'junit', version: '4.12'

 

 

package com.jojoldu.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.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;


@RunWith(SpringRunner.class)
@WebMvcTest 
public class HelloControllerTest {
    @Autowired
    private MockMvc mvc;
    
    @Test
    public void hello가_리턴된다() throws Exception {
        String hello = "hello";

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

 

  1. @RunWith(SpringRunner.class)
    1. 테스트를 진행할 때 JUnit에 내장된 실행자 외에 다른 실행자를 실행시킨다.
    2. 여기서는 SpringRunner라는 스프링 실행자를 사용한다. 즉 스프링 부트 테스트와 JUnit 사이에 연결자 역할을 함.
  2. @WebMvcTest
    1. 여러 스프링 어노테이션중 Web에 집중할 수 있는 어노테이션
    2. 전체 어노테이션의 자동완성을 중단하는 대신, MVC설정에 해당하는 자동완성만 활성화 한다
    3. @WebMvcTest annotation is used for Spring MVC tests. It disables full auto-configuration and instead apply only configuration relevant to MVC tests.
  3. @Autowired
    1. 스프링이 관리하는 Bean을 주입받음.
  4. private  MockMvc mvc
    1. 웹 API를 테스트할 떄 사용. 테스트의 시작점임
    2. 이 클래스로 HTTP GET, POST 등의 API를 테스트 할 수 있음
  5. mvc.perform(get("/hello"))
    1. MockMvc를 통해 /hello 로 HTTP GET 을 request 한다
    2. status().isOk() 
      1. mvc.perform의 결과를 검증한다. http status(200, 404, 500 등) 의 반환값을 가진다.
    3. content().string(hello)
      1. mvc.perform 의 결과를 검증한다. 본문의 내용에서 값이 맞는지 검증한다.

 


추후 추가 예정