Spring boot test 코드작성 유의점

Crow·2022년 10월 26일
0

삽질

목록 보기
1/16

한마디로 이 문제는 네이밍을 못해서 생긴 문제임

해당 내용은 참고 차원에서 적어둠
아래의 코드를 보면 @WebMvcTest(controllers = HelloControllerTest.class)

package com.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.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HelloControllerTest.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));
    }

}

@WebMvcTest 어노테이션에서 현재 클래스 자기 자신을 컨트롤러로 사용함
당연하지만 Test 클래스는 컨트롤러가 아니기 때문에
main 패키지의 컨트롤러를 사용해야함

따라서 해당 내용의 테스트를 성공하려면
@WebMvcTest(controllers = HelloController.class)이런식으로 잡아주면됨(Controller이름과 test 이름이 비슷해서 생긴 문제임)

따라서 언제나 중요한게 네이밍인거 같음

해당 내용을 찾다가 여러 삽질을함
그래들 버전을 바꾸고 junit 4버전을 사용해보고 Spring Security설정을 한다 뭐 이런거..
그래도 이번 기회에 확실히 알아두면 좋을꺼 같아서 포스팅했음

profile
어제보다 개발 더 잘하기 / 많이 듣고 핵심만 정리해서 말하기 / 도망가지 말기 / 깃허브 위키 내용 가져오기

0개의 댓글