@Getter
@RequiredArgsConstructor
public class AuthException extends RuntimeException{
private final ExceptionCode exceptionCode;
}
RuntimeException을 상속받고 ExceptionCode 필드를 가지고 있는 AuthException 클래스
@Getter
@RequiredArgsConstructor
public enum ExceptionCode {
..
UNAUTHORIZED_USER_ACCESS(HttpStatus.UNAUTHORIZED, "권한이 없는 사용자의 접근입니다!"),
private final HttpStatus httpStatus;
private final String message;
}
enum클래스인 ExceptionCode는 httpStatus와 message를 필드값으로 가짐
@Test
@DisplayName("본인이 작성하지 않은 댓글을 수정할 때 예외 발생")
void failUpdateComment() {
//given
User user = createUser();
User user2 = createUser2();
Advertisement advertisement = createAdvertisement(createtAdCreateRequest(), user);
Comment comment = createComment(user, advertisement, createCommentRequest());
CommentUpdateRequest commentUpdateRequest = createUpdateCommentRequest();
given(commentRepository.findById(any(Long.class))).willReturn(Optional.of(comment));
//when && then
Assertions.assertThatThrownBy(() -> commentService.updateComment(user2.getId(), comment.getId(), commentUpdateRequest))
.isInstanceOf(AuthException.class)
.hasFieldOrPropertyWithValue("exceptionCode", ExceptionCode.UNAUTHORIZED_USER_ACCESS);
}
작성자와 삭제하려는 유저가 다르기때문에 User객체 2개를 선언해줍니다.
Assertisons.assertThatThrownBy()에서 lamba함수로 테스트할 함수를 적어주면 됩니다.
isInstanceOf()로 AuthException.class 인지 확인
hasFieldOrPropertyWithValue(String name, Object value)
Asserts that the actual object has the specified field or property with the given value.
hasFieldOrPropertyWithValue() 로 exceptionCode필드를 가져와
ExceptionCode.UNAUTHORIZED_USER_ACCESS 인지 확인
@Test
@DisplayName("본인이 작성하지 않은 댓글을 삭제할떄 때 예외 발생")
void failDeleteComment() {
//given
User user = createUser();
User user2 = createUser2();
Advertisement advertisement = createAdvertisement(createtAdCreateRequest(), user);
Comment comment = createComment(user, advertisement, createCommentRequest());
given(commentRepository.findById(any(Long.class))).willReturn(Optional.of(comment));
//when && then
Assertions.assertThatThrownBy(() -> commentService.deleteComment(user2.getId(), comment.getId()))
.isInstanceOf(AuthException.class)
.hasFieldOrPropertyWithValue("exceptionCode", ExceptionCode.UNAUTHORIZED_USER_ACCESS);
}```