본문 바로가기

Backend/Spring & SpringBoot

Spring Boot Test하기 [1]

728x90

테스트

TDD (Test-Driven Development)

- 테스트 주도 개발에서 사용하지만, 코드의 유지보수 및 운영환경에서의 에러를 미리 방지하기 위해 단위별로 검증하는 테스트 프레임워크 

 

단위테스트

- 작성한 코드가 기대하는 대로 동작을 하는지 검증하는 절차

 

JUnit

- java기반의 단위 테스트를 위한 프레임워크

- Annotation 기반으로 테스트를 지원 Assert를 통하여 검증함.

 

서버를 구동하지 않고 컨트롤러만 단독으로 테스트하거나 컨트롤러와 연관된 비지니스 컴포넌트를 실행하지 않고 컨트롤러만 독립적으로 테스트 할 수 있는 환경이 필요. 

 

# 의존성 

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

 

# Controller : 뷰이름을 리턴해주는 Controller

@Controller //컨트롤러
public class HomeController {
	
	@GetMapping("/")//루트 경로인 /의 웹요청을 처리한다.
	public String home() {
		return "home"; // 뷰 이름을 반환한다.
	}
}

# 테스트

@SpringBootTest	
class TacoCloudApplicationTests {

	@Test
	void contextLoads() {
	}

}

여기다가 넣어서 각 메서드마다 만들기도 하지만, 따로 컨트롤러마다, 서비스, repository마다 따로 만들어서 패키지 별로 테스트함. 

 

@SpringBootTest 어노테이션 을 살펴보면 이런식으로 구현되어 있다.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@ExtendWith(SpringExtension.class)
public @interface SpringBootTest {

		~~
        
}

 

# HomeControllerTest.java

package tacos;

import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;

import tacos.controller.HomeController;

@WebMvcTest(HomeController.class)   	// <1>	어떤 클래스를 테스트하는지 
public class HomeControllerTest {

  @Autowired
  private MockMvc mockMvc;   			// <2>	mockMvc주입

  @Test
  public void testHomePage() throws Exception {
    mockMvc.perform(get("/"))    		// <3>	get("/") 을 받으면 
      .andExpect(status().isOk())  		// <4> 200 ok 를 받고
      .andExpect(view().name("home"))   // <5> view name은 home이어야 하고
      .andExpect(content().string(      // <6> content 값이 저거여야 한다는 test
          containsString("Welcome to...")))
      .andDo(print());
  }
}

 

mockMvc.perform(~) 에서 GET요청을 보내는 것이 에러 발생할 수있으므로 throws Exception추가.

- andExcept() 는 예상 값을 검증하는 메소드 status().isOk() 인지를 검증 한다. (status().isOK()는 200임) 

- view().name("home") 은 view 이름 검증 

- content().string(containsString("Welcome to..."))); 은 출력하는 결과가 맞는지 확인 

- andDo : 요청에 대한 처리 해주는 메서드, 일반적으로 print() 사용. 싹보여줌

 

# andDo(print()) 결과

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = tacos.controller.HomeController
           Method = tacos.controller.HomeController#home()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = home
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Language:"en", Content-Type:"text/html;charset=UTF-8"]
     Content type = text/html;charset=UTF-8
             Body = <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Taco Cloud</title>
  </head>
  
  <body>
    <h1>Welcome to...</h1>
    <img src="/images/TacoCloud.png"/>
  </body>
</html>
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

 

 

## RunWith이 보이지 않는 이유 ? : https://www.whiteship.me/springboot-no-more-runwith/

 

스프링 부트, @RunWith가 더이상 보이지 않는 이유

왜 최근 버전의 스프링 부트를 사용한 프로젝트의 테스트 코드에서 @RunWith를 더이상 볼 수 없는지 살펴보겠습니다.

www.whiteship.me

-> 최근 스프링 부트는 JUnit 5를 사용하기 때문에 더이상 JUnit 4에서 제공하던 @RunWith를 쓸 필요가 없고 (쓰고 싶으면 쓸 수는 있지만), @ExtendWith를 사용해야 하지만, 이미 스프링 부트가 제공하는 모든 테스트용 애노테이션에 메타 애노테이션으로 적용되어 있기 때문에 @ExtendWith(SpringExtension.class)를 생략할 수 있다.

 

728x90