티스토리 뷰

Controller Test할 때

 

요약

@WebMvcTest를 사용하면

.with(csrf())와 @WithMockUser를 사용해야 합니다.

 

@WebMvcTest
class UserControllerTest {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    UserService userService;

    @MockBean
    BCryptPasswordEncoder encoder;

    @Autowired
    ObjectMapper objectMapper;

    UserJoinRequest userJoinRequest = UserJoinRequest.builder()
            .userName("kyeongrok")
            .password("1q2w3e4r")
            .email("oceanfog1@gmail.com")
            .build();

    @Test
    @DisplayName("회원가입 성공")
    @WithMockUser
    void join_success() throws Exception {
        UserJoinRequest userJoinRequest = UserJoinRequest.builder()
                .userName("kyeongrok")
                .password("1q2w3e4r")
                .email("oceanfog1@gmail.com")
                .build();

        when(userService.join(any())).thenReturn(mock(UserDto.class));

        mockMvc.perform(post("/api/v1/users/join")
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsBytes(userJoinRequest)))
                .andDo(print())
                .andExpect(status().isOk());
    }

    @Test
    @DisplayName("회원가입 실패 - id중복")
    @WithMockUser
    void join_fail() throws Exception {

        String password = "1q2w3e4r";

        when(userService.join(any())).thenThrow(new HospitalReviewAppException(ErrorCode.DUPLICATED_USER_NAME, ""));
        when(encoder.encode(password)).thenReturn("encrypted_password");

        mockMvc.perform(post("/api/v1/users/join")
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsBytes(userJoinRequest)))
                .andDo(print())
                .andExpect(status().isConflict());
    }

    @Test
    @DisplayName("로그인 실패 - id없음")
    @WithMockUser
    void login_fail1() throws Exception {
//        String id = "kyeongrok";
//        String password = "1q2w3e4r";

        // id, pw를 보내서
        when(userService.login(any(), any()))
                .thenThrow(new HospitalReviewAppException(ErrorCode.NOT_FOUND, ""));

        // NOT_FOUND를 받으면 잘 만든 것이다
        mockMvc.perform(post("/api/v1/users/join")
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsBytes(userJoinRequest)))
                .andDo(print())
                .andExpect(status().isNotFound());
    }

 

Service Test할 때

Test Class위에 아무런 Annotation이 없습니다.

Service는 데이터 관련된 클래스나 DB에 Dependency없이 비즈니스 로직만 테스트 하는 것을 목표로 합니다.

그래서 Repository는 Mockito를 이용해 DB와 완전히 격리를 시켜 테스트를 합니다.

class HospitalServiceTest {

    private HospitalRepository hospitalRepository = Mockito.mock(HospitalRepository.class);
    private HospitalService hospitalService;

    @BeforeEach
    public void setUp() {
        hospitalService = new HospitalService(hospitalRepository);
    }

    @Test
    void getHospitalTest() {
        Hospital hospital = Hospital.builder()
                .id(1)
                .HospitalName("효치과의원")
                .roadNameAddress("광주광역시 북구 동문대로 24, 3층 (풍향동)")
                .build();
        Mockito.when(hospitalRepository.findById(1)).thenReturn(Optional.of(hospital));

        HospitalResponseDto hospitalResponseDto = hospitalService.getHospital(1);
        assertEquals(hospital.getHospitalName(), hospitalResponseDto.getHospitalName());
        assertEquals(hospital.getRoadNameAddress(), hospitalResponseDto.getRoadNameAddress());

    }
}
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함