티스토리 뷰

Spring Boot

JUnit5 Test Code 작성

LuxuryCoding 2021. 12. 17. 15:24
728x90

👍 TEST Class 생성 시 TIP

Test class 생성 방법 : 내가 만든 클래스에서 우클릭 Go To Test Create Test Ok Test폴더에 생성됨

 

👉 Intellij Live Template 단축키 생성 방법

Intellij 좌측상단 FileLive Templates 입력 → Java 에서 + 버튼 클릭 

Template test에 코드 삽입

@Test
public void $END$() throws Exception {
    //given
    
    //when
    
    //then
}

 

enter 누르기
설정이 잘 된 화면

 

클래스 파일 구조

 

build.gradle

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}

 

Controller Test

HelloController.class

@RestController
public class HelloController {

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

HelloControllerTest.class

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
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.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = HelloController.class)
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));
    }
}

@ExtendWith(SprinExtension.class)

  • @ExtendWith(SpringExtension.class) 어노테이션을 붙일 경우 Spring TestContext Framework를 Junit5 프로그래밍에 포함시킬 수 있음

@WebMvcTest(controllers = HelloController.class)

  • Web에 집중할 수 있는 어노테이션 
  • @Controller @ControllerAdvice 사용 가능 ( 왜냐하면 컨트롤러만 사용하기 때문이다.)
  • @Service, @Component, @Repository 사용 불가능

@Autowired 

  • Spring 빈을 주입 받는 것

MockMvc mvc

  • 웹 API를 테스트할 때 사용한다.
  • 스프링 MVC 테스트의 시작점
  • HTTP Method 등에 대한 API 테스트를 할 수 있다.

mvc.perform(get("hello")

  • MockMvc를 통해 /hello 주소로 get 요청을 테스트
  • 체이닝이 지원되어 여러 검증 기능을 이어서 선언 가능 ex) andExpect(status(). isOk())

andExpect(status(). isOk())

  • mvc.perform의 결과를 검증 
  • HTTP Header의 Status를 검증 200, 404, 500 
  • isOk()닌깐 200을 검증하는 코드이다.

andExpect(content(). string(hello))

  • 내용 검증 -> hello가 맞는지 검증

실행 결과

 

참고자료 : 스프링 부트와 AWS로 혼자 구현하는 웹 서비스

 

 DTO Test

HelloResponseDto.class

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class HelloResponseDto {

    private final String name;
    private final int amount;
    
}

@Getter

  • 선언된 모든 필드의 get 메서드를 생성함

@RequiredArgsContrutor

  • final 필드가 포함된 생성자를 생성해줌
  • final 필드가 없다면 필드는 생성자에 포함하지 않는다.

 

HelloResponseDtoTest.class

import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;

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에 있는 값과 동등 비교 시 같을 때만 test 성공.

JUnit assertThat이 아닌 assertj assertThat

  JUnit assertThat assertj assertThat
CoreMatchers 추가적인 라이브러리 필요 필요 없음
자동완성 IDE에서 Machers 지원이 약함 자동완성 지원이 확실하게 됨

 

실행 결과

 

HelloResponseDto를 추가한 HelloController Test

 

HelloController.class

 

@RestController
public class HelloController {

	//

    @GetMapping("/hello/dto")
    public HelloResponseDto helloDto(@RequestParam("name") String name ,@RequestParam("amount") int amount) {
        return new HelloResponseDto(name,amount);
    }
}

 

 

HelloControllerTest.class

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
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;

@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = HelloController.class)
class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

	//

    @Test
    public void helloDto_리턴() throws Exception {
        String name = "hello";
        int amount = 1200;

        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)));
    }
}

JsonPath

  • Json 응답 값을 필드별로 검증할 수 있는 메서드
  • $를 기준으로 필드명을 명시

 

실행결과

댓글
최근에 달린 댓글
최근에 올라온 글
Total
Today
Yesterday
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30