Backend/JUnit & BDD

MockTest 시 null 값이 뜨는 이유

th42500 2023. 1. 26. 11:55

❓ 발생한 문제

좋아요 기능 테스트 진행 중 Result에 Null 값이 담겨 테스트에 실패하게 되었다.

 

🔎 왜 Null값이 담길까?

RecipeRestControllerTest.java
RecipeRestController.java

원인을 알아보고자 디버깅을 통해 RecipeRestControllerTest.java 와 RecipeRestController.java 에서의 userName이 다르다는 것을 확인할 수 있었다.

 

 

💡 해결 방법

@WithMockUser 에 테스트하고자 하는 userName을 설정해줌으로써 해결할 수 있었다.

package com.woowahan.recipe.controller.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woowahan.recipe.domain.dto.recipeDto.*;
import com.woowahan.recipe.fixture.TestInfoFixture;
import com.woowahan.recipe.service.RecipeService;
import org.junit.jupiter.api.*;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;

import java.time.LocalDateTime;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
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.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(RecipeRestController.class)
@WithMockUser(username = "testUser")  // ✨
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)  // 언더로 표시한 부분 공백 표시
class RecipeRestControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    RecipeService recipeService;

    @Autowired
    ObjectMapper objectMapper;

    @Nested
    @DisplayName("좋아요 테스트")
    class LikeTest {

        @Test
        @DisplayName("좋아요 누르기 테스트")
        void pushLikeTest() throws Exception {
            // given
            Long recipeId = TestInfoFixture.get().getRecipeId();
            String userName = TestInfoFixture.get().getUserName();
            String pushLikesMessage = "좋아요를 눌렀습니다.";

            // when
            given(recipeService.pushLikes(recipeId, userName)).willReturn(pushLikesMessage);

            // then
            mockMvc.perform(post(String.format("/api/v1/recipes/{id}/likes"), recipeId)
                    .with(csrf()))
                    .andDo(print())
                    .andExpect(jsonPath("$.resultCode").value("SUCCESS"))
                    .andExpect(jsonPath("$.result").value("좋아요를 눌렀습니다."));
        }

        @Test
        @DisplayName("좋아요 취소 테스트")
        void cancelLikeTest() throws Exception {
            // given
            Long recipeId = TestInfoFixture.get().getRecipeId();
            String userName = TestInfoFixture.get().getUserName();

            // when
            given(recipeService.pushLikes(recipeId, userName)).willReturn("좋아요를 취소합니다.");

            // then
            mockMvc.perform(post(String.format("/api/v1/recipes/{id}/likes"), recipeId)
                    .with(csrf()))
                    .andDo(print())
                    .andExpect(jsonPath("$.resultCode").value("SUCCESS"))
                    .andExpect(jsonPath("$.result").value("좋아요를 취소합니다."));
        }
    }
}