상세 컨텐츠

본문 제목

[S.A혼구웹 / Test] Junit5 사용해보기

Web/Spring

by 감싹이 2023. 1. 23. 23:27

본문

설 연휴동안 < 스프링부트와 AWS로 혼자 구현하는 웹서비스 > 보면서 공부 중..

책은 JUnit4로 되어있는데 나는 JUnit5 사용 예정

JUnit5도 처음이고 테스트코드도 처음 작성해보는 거라 나중에 또 보려고 기록한다.....

매우 두서없고 불친절한 글이라는 뜻

 

Gradle 설정

dependencies {
             testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1'
             testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1'
}

tasks.named('test') {
             useJUnitPlatform()
}

책이 2019년에 발행된 터라 JUnit4로 되어있다.. 요즘은 JUnit5를 쓰는 게 보편적인 것 같아서 열심히 찾아보고 수정 중

 

Controller Test

package com.project.freelecspringbootwebservice.web;

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 org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@ExtendWith(SpringExtension.class) //JUnit4에서는 @RunWith 사용
@WebMvcTest(controllers = HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void hello() throws Exception{
        String hello = "hello";

        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/hello");
        mvc.perform(builder)
                .andExpect(status().isOk())
                .andExpect(content().string(hello));

    }

}

책에 나온대로 perform(get("/hello"))로 하면 get에 빨간 줄이 뜬다

구글링 하다가 MockHttpServletRequestBuilder를 이용하면 에러가 안난다는 강같은 답변 발견 !

위와같이 작성하면 test 성공이 무사히 뜬다

원인은 책 다 보고 추가 공부해보는 걸로..

 

DTO 테스트 : assertThat

package com.project.freelecspringbootwebservice.web.dto;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class HelloResponseDtoTest {
    
    @Test
    public void lombok(){
        String name = "test";
        int amount = 1000;
        
        HelloResponseDto dto = new HelloResponseDto(name, amount);

        //assertThat : assertj라는 테스트검증 라이브러리 검증 메소드
            //검증하고 싶은 대상을 메소드 인자로 받음
        //isEqualTo : assertThat에 있는 값과 isEqualTo의 값을 비교해서 같을 때만 성공
        assertThat(dto.getName()).isEqualTo(name); 
    }
}

JUnit assertThat이랑 assertj의 assertThat이 있는 모양

assertj의 장점 

(1) CoreMatchers와 달리 추가적으로 라이브러리가 필요하지 않다
(2) 자동완성이 좀 더 확실하게 지원된다

라고 한다

 

Hamcrest (JUnit5에서 더이상 지원하지 않음)

이런......

JUnit4에는 기본 패키지 포함이지만 JUnit5부터는 별도로 프로젝트에 추가해야 사용할 수 있단다...

어차피 간단한 테스트라 name, amount 를 value 메서드로 체이닝해 검사할 수 있는 것 같아서 해봄

이게 is()랑 같은 건진 아직 잘 모르겠다

이것도 나중에 공부해봐야지 ( 참고 )

암튼 테스트 성공

package com.project.freelecspringbootwebservice.web;

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 org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@ExtendWith(SpringExtension.class) //JUnit4에서는 @RunWith 사용
@WebMvcTest(controllers = HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void hello() throws Exception{
        String hello = "hello";

        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/hello");
        mvc.perform(builder)
                .andExpect(status().isOk())
                .andExpect(content().string(hello));

    }

    @Test
    public void helloDto() throws Exception{
        String name = "hello";
        int amount = 1000;

        MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/hello/dto").param("name", name).param("amount", String.valueOf(amount));
        mvc.perform(builder)
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name").value(name))
                .andExpect(jsonPath("$.amount").value(amount));


    }

}

 

** HamCrest

- 객체 타입을 검사할 수 있다
- 두 객체의 참조가 같은 인스턴스인지 검사할 수 있다

등등..의 역할을 해서 추가해서 쓰면 좋긴 하다는 말을 봤다

나중에 또 공부해서 써봐야지

 

 

관련글 더보기