Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

Kuma's Curious Paradise

JUnit과 AssertJ의 차이점 본문

스프링

JUnit과 AssertJ의 차이점

쿠마냥 2024. 5. 25. 23:19

JUnit과 AssertJ는 모두 단위 테스트 용 라이브러리로, 테스트 작성에 많은 도움을 준다. 다음과 같이 의존성을 추가하면 스프링은 JUnit, AssertJ, Mockito 등 다양한 테스트 라이브러리를 함께 불러온다.

testImplementation 'org.springframework.boot:spring-boot-starter-test'

 

이러한 기본 설정은 두 라이브러리가 모두 필요함을 의미할 것이다. 보통은 AssertJ를 사용해서 테스트 코드를 작성하라는 이야기를 많이 하는데, 이번 기회에 두 라이브러리의 차이점에 대해 알아보려 한다.

1. JUnit

 

위의 스크린샷을 보면, junit 밑에 jupiter.api 라는 것이 존재한다. junit5가 보급되면서 구조가 변경되었고 그 과정에서 ‘jupiter’라는 모듈이 새로 생긴 것.

1-1. JUnit5의 구성

Junit5는 크게 3가지 모듈로 구성된다.

  1. JUnit Platform: 테스트를 발견하고 실행하는 테스트 엔진.
  2. JUnit Jupiter: 테스트 코드 작성에 필요한 API(jupiter-api) + 테스트 실행에 필요한 엔진(jupiter-engine).
  3. JUnit Vintage: JUnit 3, 4 하위 호환을 위한 모듈.

1-2. JUnit 어노테이션

@Test

@RepeatedTest

@PrameterizedTest

@BeforeAll

@BeforeEach

@AfterAll

@AfterEach

@Disabled

1-3. JUnit의 Assertions 클래스

  • assertEquals(expected, actual)
  • assertNotEquals(unexpected, actual)
  • assertArrayEquals(expected, actual)
  • assertNull(actual)
  • assertNotNull(actual)
  • assertTrue(condition)
  • assertFalse(condition)
  • assertThrows(expectedType, executable)
  • assertAll()

2. AssertJ

AssertJ는 JUnit의 Assertion 기능을 더욱 풍부하게 제공하는 라이브러리이다. 가독성도 좋고 직관적인 assert가 가능하다.

2-1. 장점

  1. 더 읽기 쉽다 : assertThat + 메서드 체이닝 으로 자연어에 더 가깝다.
  2. 기능이 많다 : 컬렉션, 배열, 예외 등 다양한 조건 검증이 가능하다.
  3. 메서드 체이닝을 지원한다 : 여러 속성을 한 번에 검사하는 게 가능하다. list의 size를 확인하면서 동시에 'a'라는 컴포넌트를 포함하는지 확인할 수 있다. 

2-2. Assertions 클래스

  • assertThat(actual).isEqualTo(expected)
  • assertThat(actual).isNotEqualTo(unexpected)
  • assertThat(actual).isNull()
  • assertThat(actual).isNotNull()
  • assertThat(condition).isTrue()
  • assertThat(condition).isFalse()
  • assertThat(actual).hasSize(expectedSize)
  • assertThat(actual).contains(expectedElement)
  • assertThat(actual).containsExactly(expectedElements)

결론

JUnit은 주로 테스트 실행, 수명 주기 관리, 기본적인 단언 기능을 제공한다. 반면 AssertJ는 테스트 코드를 더욱 간결하고 읽기 쉽게 만드는 기능을 제공한다. 코드를 쓸 때 assertJ를 사용하라는 이유는 여기에 있는 듯! 테스트 코드를 작성해 보면서 적절한 라이브러리를 적용하는 연습을 더 필요하겠다.