[TIL] 9월 7일

yeon·2021년 9월 8일
0

MockMvc 사용 시 한글 깨짐 문제 해결

MockMvc를 이용해서 Controller의 전체 카테고리 조회 기능을 테스트했다. 아래의 코드로 진행하였고 print()로 response body를 출력했을 때 한글이 깨진다.

테스트는 통과하였지만 한글 깨짐 문제를 해결하는 편이 좋을거 같다고 생각했다.

@Test
@DisplayName("전체 카테고리 조회 기능 테스트")
void showAllCategories() throws Exception {

    List<MainCategory> mainCategoryList = new ArrayList<>();
    mainCategoryList.add(new MainCategory("채소"));
    mainCategoryList.add(new MainCategory("과일/견과/쌀"));
    mainCategoryList.add(new MainCategory("수산/해산/건어물"));
    mainCategoryList.add(new MainCategory("정육/계란"));

    Mockito.when(categoryService.getCategories()).thenReturn(mainCategoryList);

    mockMvc.perform(get("/api/categories"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.data.categories").isArray())
						.andDo(print());
}

한글이 깨진다..

MockMvc 설정 시 CharacterEncodingFilter를 추가한다.

아래와 같이 `WebApplicationContext 를 주입받고 mockMvc를 setUp() 과 같이 설정해준다.

한글 깨짐 이슈를 해결할 수 있다.

alwaysDo() 메서드를 이용해서 항상 수행할 동작을 지정할 수도 있다.

@WebMvcTest(CategoryController.class)
@Import(value = {TokenProvider.class, TokenExtractor.class})
class CategoryControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext ctx;

    @MockBean
    private CategoryService categoryService;

    @BeforeEach
    void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(ctx)
                .addFilters(new CharacterEncodingFilter("UTF-8", true))
                .alwaysDo(print())
                .build();
    }

    @Test
    @DisplayName("전체 카테고리 조회 기능 테스트")
    void showAllCategories() throws Exception {

        List<MainCategory> mainCategoryList = new ArrayList<>();
        mainCategoryList.add(new MainCategory("채소"));
        mainCategoryList.add(new MainCategory("과일/견과/쌀"));
        mainCategoryList.add(new MainCategory("수산/해산/건어물"));
        mainCategoryList.add(new MainCategory("정육/계란"));

        Mockito.when(categoryService.getCategories()).thenReturn(mainCategoryList);

        mockMvc.perform(get("/api/categories"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.categories").isArray());
    }
}

한글 깨짐 현상이 사라졌다.

참고: https://github.com/HomoEfficio/dev-tips/blob/master/Spring Test MockMvc의 한글 깨짐 처리.md

참고한 글에서는 WebApplicationContext 를 주입받으려면 WebMvcTest가 아닌 SpringBootTest로 실행해야한다는데 나는 에러없이 동작한다.... MockMvcTest를 실행할 때 WebApplicationContext는 주입받을 수 있게 바뀐건가 싶어서 검색해봤는데 찾지 못했다.


오늘 한일

0개의 댓글