본문 바로가기
개발/Spring

오류 처리

by BellOne4222 2024. 2. 19.

비즈니스 로직에서 발생 할 수 있는 문제들에 대한 알맞는 에러 처리 방법

  • 에러 코드 테스트
class ErrorCodeTest {

	// 매개변수화된 테스트를 정의합니다.
	@ParameterizedTest(name = "[{index}] {0}의 HttpStatus는 {1}이다.")
	// @MethodSource를 사용하여 테스트 메서드의 인자를 제공하는 메서드를 지정합니다.
	@MethodSource
	// 테스트의 표시 이름을 설정합니다.
	@DisplayName("예외를 받으면, 예외 메시지가 포함된 메시지 출력")
	void givenExceptionWithMessage(ErrorCode sut, String expected) {
		// 예외 메시지를 확인하는 테스트입니다.

		// Given
		// 예외 객체를 생성합니다.
		Exception e = new Exception("This is a test exception");

		// When
		// ErrorCode에서 예외 메시지를 가져옵니다.
		String actual = sut.getMessage(e);

		// Then
		// 예상된 메시지와 실제 메시지가 같은지 확인합니다.
		assertThat(actual).isEqualTo(expected);
	}

	// 예외 메시지를 확인하는 테스트에 필요한 인자를 제공하는 메서드입니다.
	static Stream<Arguments> givenExceptionWithMessage() {
		return Stream.of(
			// 테스트 케이스와 예상 결과를 제공합니다.
			arguments(ErrorCode.OK, "This is a test exception"),
			arguments(ErrorCode.BAD_REQUEST, "Bad request - This is a test exception"),
			arguments(ErrorCode.SPRING_BAD_REQUEST, "Spring-detected bad request - This is a test exception"),
			arguments(ErrorCode.VALIDATION_ERROR, "Validation error - This is a test exception"),
			arguments(ErrorCode.INTERNAL_ERROR, "Internal error - This is a test exception"),
			arguments(ErrorCode.SPRING_INTERNAL_ERROR, "Spring-detected internal error - This is a test exception")
		);
	}





}



  • 예외 처리 로직 입출력 테스트(ConstraintViolationException 예외)
// ApiExceptionHandlerTest

@DisplayName("핸들러 - API 에러 처리")
class ApiExceptionHandlerTest {

	private ApiExceptionHandler sut;
	private WebRequest webRequest;

	// 각 테스트 메서드 실행 전에 수행할 설정을 정의합니다.
	@BeforeEach
	void setUp() {
		sut = new ApiExceptionHandler(); // ApiExceptionHandler 객체를 초기화합니다.
		webRequest = new DispatcherServletWebRequest(new MockHttpServletRequest()); // MockHttpServletRequest를 사용하여 WebRequest를 초기화합니다.
	}

	// 검증 오류에 대한 응답 데이터를 정의하는 테스트입니다.
	@DisplayName("검증 오류 - 응답 데이터 정의")
	@Test
	void givenValidationException_whenHandlingApiException_thenReturnsResponseEntity() {
		// Given
		// 검증 예외 객체를 생성합니다.
		ConstraintViolationException e = new ConstraintViolationException(Set.of());

		// When
		// 검증 예외를 처리하고 응답을 받습니다.
		ResponseEntity<Object> response = sut.validation(e, webRequest);

		// Then
		// 응답이 예상된 대로 되는지 확인합니다.
		assertThat(response)
			.hasFieldOrPropertyWithValue("body", ApiErrorResponse.of(false, ErrorCode.VALIDATION_ERROR, e))
			.hasFieldOrPropertyWithValue("headers", HttpHeaders.EMPTY)
			.hasFieldOrPropertyWithValue("statusCode", HttpStatus.BAD_REQUEST);
	}
}

 

 

 

'개발 > Spring' 카테고리의 다른 글

비즈니스 로직 테스트  (0) 2024.02.20
spring boot properties  (0) 2024.02.20
Validation  (0) 2024.02.19
MVC 패턴(3) - 비즈니스 로직 구현  (0) 2024.02.19
Test Driven Development(TDD)  (1) 2024.02.18