2021年1月5日星期二

Why does the unit test fail?

I'm a new developer. Can you tell me why you failed the unit test while practicing?

Here is UserController.java

@RequiredArgsConstructor  @RestController  public class UserController {    private final UserService userService;    @PostMapping(value="/v1/user")  public ResponseEntity<ResponseDto> postUser(@RequestBody UserSaveRequestDto userSaveRequestDto) {      Long userId = userService.insertUser(userSaveRequestDto);        return CommonUtil.getResponseEntity(UserResponseDto.builder()                                                              .userId(userId)                                                              .build()                                                              , HttpStatus.OK                                                              , "회원 등록 완료");  }    }  

Here is UserControllerTest.java

given(userService.insertUser(userSaveRequestDto)).willReturn(1L); // not working

so ".andExpect(jsonPath("$.data.userId").value("1"))" is fail

Please let me know why given() doesn't work.

@WebMvcTest  public class UserControllerTest {    MockMvc mockMvc;    @MockBean // Mock Bean은 Mock과 달리 Container가 관리하도록 빈을 만듬, 일반적으로 MockMvc와 많이씀  UserService userService;    @Autowired  ObjectMapper objectMapper;    @Autowired  private WebApplicationContext ctx;    UserSaveRequestDto userSaveRequestDto;    @BeforeEach  void setUp() {      mockMvc = MockMvcBuilders.webAppContextSetup(ctx)          .addFilters(new CharacterEncodingFilter("UTF-8", true))  // 한글 깨짐 처리          .build();        userSaveRequestDto = UserSaveRequestDto.builder()          .userName("test")          .userPhoneNumber("01026137832")          .build();  }    @DisplayName("MockMvc를 이용한 postUser slice 테스트")  @Test  public void postUserTest() throws Exception {      // given      given(userService.insertUser(userSaveRequestDto)).willReturn(1L); // Controller가 의존하고 있는 Service객체의 행동을 설정 해준다.      String content = objectMapper.writeValueAsString(userSaveRequestDto); // dto to json        // when      ResultActions resultActions = mockMvc.perform(post("/v1/user")                      .contentType(MediaType.APPLICATION_JSON)                      .content(content));        // then      resultActions          // ResultActions 객체의 andDo, andExpect, andReturn 메서드 사용          .andDo(result -> {              if (result.getResolvedException() != null) {                  result.getResolvedException().printStackTrace();              }          })          .andExpect(status().isOk())          .andExpect(jsonPath("$.data.userId").value("1"))          .andExpect(jsonPath("$.message").value("회원 등록 완료"));      }     }  
https://stackoverflow.com/questions/65589215/why-does-the-unit-test-fail January 06, 2021 at 10:04AM

没有评论:

发表评论