[Spring] Class Assertions

2024. 1. 24. 20:33Backend/Spring

📝 인프런에서 강의를 하고 계시는 김영한 님의 Spring Framework를 공부하고 있습니다. 틀리거나 다른 부분이 있을 수 있습니다.

 

스프링 공부를 하면서, test 코드의 중요성을 확인하고 있다.

강의에서 제공된 @Test를 진행하면서 Assertions에 대한 내용이 있길래, 개인적으로 참고하고자 블로그 등을 참고해서 정리를 해두려고 한다.

 

 

0. Class Assertions

- 다음 사이트 ( http://www.javadoc.io ) 에서는 Class Assertions을 다음과 같이 소개한다.

This class only contains all assertThat methods, if you have ambiguous method compilation error, use either AssertionsForClassTypes or AssertionsForInterfaceTypes and if you need both, fully qualify you assertThat method.

 

- JUnit 사이트 ( https://junit.org/junit5/ )에서는 다음과 같이 소개하고 있다.

Assertions is a collection of utility methods that support asserting conditions in tests.
Unless otherwise noted, a failed assertion will throw an AssertionFailedError or a subclass thereof.

 

test 할 때 사용할 수 있는 클래스이다.  그 중에서 강의에서 나왔던 두 메서드는 다음과 같다.

 

1. assertThat ( 참고자료 )

import static org.assertj.core.api.Assertions.assertThat;

 

테스트할 때 사용되며, assertThat(테스트할 대상).메서드().메서드() 이런 식으로 호출하며 사용한다.

assertThat(테스트 대상).isEqualTo(expected);

 

 

2. assertThrow ( 참고자료 )

import static org.junit.jupiter.api.Assertions.assertThrows;

 

테스트할 때 사용되는데, 에러 관련 테스트를 할 때 사용된다.

assertThrows(에러 클래스, 에러를 발생하게 할 로직)

 

 

References

1. 김영한 [스프링 핵심원리 - 기본편] 

2. UnitTest에서 사용하는 AssertJ의 AssertThat이란?

3. JUnit5 예외 테스트코드 작성 (assertThrows)