본문 바로가기

스프링 스터디

Controller 통합 테스트 코드 작성 / 2022-02-18

그동안 작성한 기능들을 테스트하기 위한 테스트 코드를 작성하였다. 기능 - 에러를 세트로 구현한다.

 

 

 

테스트를 위해 필요한 기본 세팅이다.

    MockMvc mvc;

    @Autowired
    private WebApplicationContext context;

    @BeforeEach
    public void setUp(){
        mvc= MockMvcBuilders
                .webAppContextSetup(context)
                .addFilters(new CharacterEncodingFilter("UTF-8", true))
                .build();
    }

 

 

 

 

 

  • 게시글 생성
    @Test
    public void 게시글_생성() throws Exception{
        PostRequestDto postRequestDto = new PostRequestDto("testTtile","testContent");
        mvc.perform(post("/posts-ywoo/1")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content(new ObjectMapper().writeValueAsString(postRequestDto)))
                .andExpect(status().isOk())
                .andDo(print());
    }

    @Test
    public void 게시글_생성_NotFound_error() throws Exception{
        PostRequestDto postRequestDto = new PostRequestDto("testTtile","testContent");
        mvc.perform(post("/posts-ywoo/10")
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON)
                        .content(new ObjectMapper().writeValueAsString(postRequestDto)))
                .andExpect(status().isNotFound())
                .andDo(print());
    }

게시글 생성은 경로 변수로 유저의 아이디를 받고, body로 생성할 데이터를 받는다. 

  • contentType() : 데이터는 application/json 형태로 받기 때문에 json 타입으로 설정한다.
  • content(new ObjectMapper().writeValueAsString()) : 넣을 데이터를 string형으로 바꿔준다.
  • andExpect(status().isOk()) : 테스트를 실행한 후 응답을 받을 코드이다. 성공시 isOk를 받는다.
    • 에러를 테스트할 경우에는 해당되는 에러의 코드로 바꿔준다. 404 NotFound와 같은 에러를 발생시킬 경우 isNotFound()를 사용한다.
  • andDo(print()) : 실행 결과를 알려준다.

 

  • 게시글 전체 조회
    @Test
    public void 게시글_전체조회() throws Exception{
        mvc.perform(get("/posts-ywoo")
                .param("userpk","1"))
                .andExpect(status().isOk())
                .andDo(print());
    }

게시글 전체 조회와 같은 경우는 찾는 게시글이 없을 경우 에러를 발생시키는 것이 아닌 빈 값을 보내주기 때문에 에러 테스트를 하지 않는다.

 

  • param() : requestParam으로 들어온 변수를 테스트할 때 사용한다.

 

 

  • 게시글 상세 조회
    @Test
    public void 게시글_상세조회() throws Exception{
        mvc.perform(post("/posts-ywoo/details/1"))
                .andExpect(status().isOk())
                .andDo(print());
    }

    @Test
    public void 게시글_상세조회_NotFoundError() throws Exception{
        mvc.perform(post("/posts-ywoo/details/10"))
                .andExpect(status().isNotFound())
                .andDo(print());
    }

 

 

 

  • 게시글 수정
@Test
public void 게시글_수정() throws Exception{
    PostRequestDto postRequestDto = new PostRequestDto("hello","goodbye");
    mvc.perform(put("/posts-ywoo/1")
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)
            .content(new ObjectMapper().writeValueAsString(postRequestDto)))
            .andExpect(status().isOk())
            .andDo(print());
}

@Test
public void 게시글_수정_NotFoundError() throws Exception{
    PostRequestDto postRequestDto = new PostRequestDto("hello","goodbye");
    mvc.perform(put("/posts-ywoo/10")
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .content(new ObjectMapper().writeValueAsString(postRequestDto)))
            .andExpect(status().isNotFound())
            .andDo(print());
}

 

 

 

 

  • 게시글 삭제
@Test
public void 게시글_삭제() throws Exception{
    mvc.perform(delete("/posts-ywoo/1"))
            .andExpect(status().isOk())
            .andDo(print());
}
@Test
public void 게시글_삭제_NotFoundError() throws Exception{
    mvc.perform(delete("/posts-ywoo/10"))
            .andExpect(status().isNotFound())
            .andDo(print());
}

 

 

 


 

 

 

전체 코드

package com.second.spring_study.controller.post;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.second.spring_study.dto.request.ywoo.PostRequestDto;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;


@Transactional
@SpringBootTest
public class PostYwooControllerTest {
    MockMvc mvc;

    @Autowired
    private WebApplicationContext context;

    @BeforeEach
    public void setUp(){
        mvc= MockMvcBuilders
                .webAppContextSetup(context)
                .addFilters(new CharacterEncodingFilter("UTF-8", true))
                .build();
    }

    @Test
    public void 게시글_생성() throws Exception{
        PostRequestDto postRequestDto = new PostRequestDto("testTtile","testContent");
        mvc.perform(post("/posts-ywoo/1")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content(new ObjectMapper().writeValueAsString(postRequestDto)))
                .andExpect(status().isOk())
                .andDo(print());
    }

    @Test
    public void 게시글_생성_NotFound_error() throws Exception{
        PostRequestDto postRequestDto = new PostRequestDto("testTtile","testContent");
        mvc.perform(post("/posts-ywoo/10")
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON)
                        .content(new ObjectMapper().writeValueAsString(postRequestDto)))
                .andExpect(status().isNotFound())
                .andDo(print());
    }

    @Test
    public void 게시글_전체조회() throws Exception{
        mvc.perform(get("/posts-ywoo")
                .param("userpk","1"))
                .andExpect(status().isOk())
                .andDo(print());
    }

    @Test
    public void 게시글_상세조회() throws Exception{
        mvc.perform(post("/posts-ywoo/details/1"))
                .andExpect(status().isOk())
                .andDo(print());
    }

    @Test
    public void 게시글_상세조회_NotFoundError() throws Exception{
        mvc.perform(post("/posts-ywoo/details/10"))
                .andExpect(status().isNotFound())
                .andDo(print());
    }

    @Test
    public void 게시글_수정() throws Exception{
        PostRequestDto postRequestDto = new PostRequestDto("hello","goodbye");
        mvc.perform(put("/posts-ywoo/1")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content(new ObjectMapper().writeValueAsString(postRequestDto)))
                .andExpect(status().isOk())
                .andDo(print());
    }

    @Test
    public void 게시글_수정_NotFoundError() throws Exception{
        PostRequestDto postRequestDto = new PostRequestDto("hello","goodbye");
        mvc.perform(put("/posts-ywoo/10")
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON)
                        .content(new ObjectMapper().writeValueAsString(postRequestDto)))
                .andExpect(status().isNotFound())
                .andDo(print());
    }

    @Test
    public void 게시글_삭제() throws Exception{
        mvc.perform(delete("/posts-ywoo/1"))
                .andExpect(status().isOk())
                .andDo(print());
    }
    @Test
    public void 게시글_삭제_NotFoundError() throws Exception{
        mvc.perform(delete("/posts-ywoo/10"))
                .andExpect(status().isNotFound())
                .andDo(print());
    }
}

 

 

 


🔗 : ISSUES #45 Controller 통합 테스트 코드 작성

🔗 : Spring Study