[개발] - Spring/Test Code
20230210 테스트 코드 추가 설명 (4) 프로필 정보 조회 실패 테스트
완벽한 장면
2023. 2. 16. 11:10
원본 소스 코드
UserService
public interface UserService {
ProfileResponseDto showProfile(Long profileId);
}
UserServiceImpl
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService { // UserServiceImpl로 수정 부탁드립니다.
private final UserRepository userRepository;
private final JwtUtil jwtUtil;
private final PasswordEncoder passwordEncoder;
@Override
public ProfileResponseDto showProfile(Long userId) {
Profile profile = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("회원 없음")).getProfile();
return new ProfileResponseDto(profile);
}
}
사용자 정보 조회 성공 테스트 코드 그대로 따오면
@ExtendWith(MockitoExtension.class)
class UserServiceImplTest {
@Mock
UserRepository userRepository;
@InjectMocks
UserServiceImple userService;
@Test
@DisplayName("회원정보 조회 성공 테스트")
void showProfile() {
//given
Long userId = 1L; // 데이터베이스에 저장되어 있는 사용자의 primary key
// 데이터베이스에 저장되어 있는 사용자의 역할
User user = new User("testUser", "1234", new Profile("banana", "before"));
given(userRepository.findById(userId).willReturn(Optional.of(user));
//when
ProfileResponseDto responseDto = userService.showProfile(userId);
//then
assertThat(responseDto.getNickname()).isEqualTo(user.getProfile().getNickname());
assertThat(responseDto.getImg_url()).isEqualTo(requestDto.getProfile().getImg_url());
}
}
한땀 한땀 또 받아적으면서 코딩.
이 때도 마찬가지로 데이터베이스에 사용자 정보가 없는 것이니까.
// 데이터베이스에 저장되어 있는 사용자 역할 부분은 날려준다.
역시 정보 요청을 하면 Optional 로 데이터를 감싸는 게 아니라, 비어있는 Optional 을 주겠지(Optional.empty())
그리고 회원정보 업데이트 실패 테스트와 같은 형식으로 본문의 when, then을 꾸며주면 된다.
@ExtendWith(MockitoExtension.class)
class UserServiceImplTest {
@Mock
UserRepository userRepository;
@InjectMocks
UserServiceImple userService;
@Test
@DisplayName("회원정보 조회 실패 테스트 : 회원 정보가 없는 경우")
void failsshowProfile() {
//given
Long userId = 1L; // 데이터베이스에 저장되어 있는 사용자의 primary key
given(userRepository.findById(userId).willReturn(Optional.empty());
assertThatThrownBy(() -> {
userService.showProfile(userId); // when
}).isInstanceOf(IllegalArgumentException.class); // then
}
}
}
728x90
반응형