본문 바로가기
스프링/JUnit

[Junit] AssertJ란?

by 책 읽는 개발자_테드 2021. 10. 30.
반응형

학습 목표

· AsserJ란?

· AsserJ의 장점

· TODO: AssertJ의 단점

· 라이브러리 의존성 설정

· AssertJ 메소드 임포트

· 사용 방법

· 잘못된 사용 예시


AsserJ란?

· 단언문(assertion)을 작성하기 위한 풍부한 인터페이스를 제공하는 자바 라이브러리로,

  테스트 코드의 가독성을 향상시키고 테스트 유지 관리를 더 쉽게 만드는 것을 주요 목적으로 한다.

· JUnit의 단언에 대한 표현력 부족을 보완한다.

· spring-boot-starter-test에 기본적으로 포함된다.

 

AssertJ의 장점

· 메서드 체이닝을 지원하여 깔끔하고 읽기 쉬운 테스트 코드를 작성 가능하다.

· 타입별로 다양한 검증 메서드를 제공한다.

   - 개발자가 테스트를 하면서 필요하다고 상상할 수 있는 거의 모든 메서드 제공

TODO: AssertJ가 Junit의 assertThat 보다 편리한 이유 https://www.youtube.com/watch?v=zLx_fI24UXM&t=7s 

 

TODO: AssertJ의 단점

 

라이브러리 의존성 설정

· 자바8 이상은 3.x 버전을, 자바7 이하는 2.x 버전을 사용

 

· Gradle

testCompile 'org.assertj:assertj-core:3.6.2' //자바8 이상
testCompile 'org.assertj:assertj-core:2.6.0' //자바7 이하

 

· Maven

<dependency>
  <groupId>org.assertj</groupId>
  <artifactId>assertj-core</artifactId>
  <version>3.6.2</version>
  <scope>test</scope>
</dependency>

 

AssertJ 메소드 임포트

· 정적 임포트를 통해 AssertJ의 API를 클래스 이름없이 바로 사용할 수 있음

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

 

사용 방법

· 모든 테스트 코드는 assertThat() 메서드로 시작하고, 메서드 체인을 이용하여 코드 작성

assertThat(테스트 타켓).메소드1().메소드2().메소드3();

 

· 문자열 테스트

assertThat("Hello, world! Nice to meet you.") // 주어진 "Hello, world! Nice to meet you."라는 문자열은
				.isNotEmpty() // 비어있지 않고
				.contains("Nice") // "Nice"를 포함하고
				.contains("world") // "world"도 포함하고
				.doesNotContain("ZZZ") // "ZZZ"는 포함하지 않으며
				.startsWith("Hell") // "Hell"로 시작하고
				.endsWith("u.") // "u."로 끝나며
				.isEqualTo("Hello, world! Nice to meet you."); // "Hello, world! Nice to meet you."과 일치합니다.

 

· 숫자 테스트에 대하여 대소 비교오프셋을 이용한 느슨한 비교가 가능

assertThat(3.14d) // 주어진 3.14라는 숫자는
				.isPositive() // 양수이고
				.isGreaterThan(3) // 3보다 크며
				.isLessThan(4) // 4보다 작습니다
				.isEqualTo(3, offset(1d)) // 오프셋 1 기준으로 3과 같고
				.isEqualTo(3.1, offset(0.1d)) // 오프셋 0.1 기준으로 3.1과 같으며
				.isEqualTo(3.14); // 오프셋 없이는 3.14와 같습니다

 

· 예외(Exception 처리): assertThatThrownBy()

assertThatThrownBy(() -> {
    List<String> list = Arrays.asList("String one", "String two");
    list.get(2);
}).isInstanceOf(IndexOutOfBoundsException.class)
  .hasMessageContaining("Index: 2, Size: 2");

 

· 예외가 발생 안함을 단언

assertThatCode(()-> {
    List<String> list = Arrays.asList("String one", "String two");
    list.get(0);
}).doesNotThrowAnyException();

 

TODO: 날짜/시간에 대한 검증, LocalDateTime/OffsetDateTime/ZonedDateTime 타입에 대한 추가 검증, 콜렉션에 대한 검증 관련 검증 https://incheol-jung.gitbook.io/docs/study/undefined-3/d.-assertj

 

잘못된 사용 예시

 

· 아무것도 단언하지 않는 경우

// 잘못된 사용 - 아무것도 단언하지 않는다.
assertThat(actual.equals(expected));

// 올바른 사용
assertThat(actual).isEqualTo(expected);

// 올바른 사용 2
assertThat(actual.equals(expected)).isTrue();

 

· 아무것도 단언하지 않고, 통과시키지 않는 경우

// 잘못된 사용: 아무것도 단언하지 않고, 통과시키지 않음
assertThat(1 == 2);

// 올바른 사용
assertThat(1).isEqualTo(2);

// 올바른 사용 2
assertThat(1 == 2).isTrue();

 

· as와 describedAs 메서드는 assertion 후에는 아무런 효과가 없음

   - assertion 전에 as와 describedAs 메서드를 사용해야함

   - as와 describedAs 메서드는 테스트에 설명을 붙임

// 잘못된 사용: as와 describedAs 메서드는 assertion 후에는 아무런 효과가 없다
assertThat(actual).isEqualTo(expected).as("description");
assertThat(actual).isEqualTo(expected).describedAs("description");

// 올바른 사용: assersion 전에 as와 describedAs 메서드를 사용해야한다
assertThat(actual).as("description").isEqualTo(expected);

// 올바른 사용 2
assertThat(actual).describedAs("description").isEqualTo(expected);

 

· overridingErrorMessage/withFailMessage 메서드는 assertion 후에 아무런 효과가 없음

   - assertion 전에 overridingErrorMessage/withFailMessage 메서드를 사용해야함

// 잘못된 사용: overridingErrorMessage/withFailMessage 메서드는 assertion 후에 아무런 효과가 없다
assertThat(actual).isEqualTo(expected).overridingErrorMessage("custom error message");
assertThat(actual).isEqualTo(expected).withFailMessage("custom error message");

// 올바른 사용
assertThat(actual).overridingErrorMessage("custom error message").isEqualTo(expected);
assertThat(actual).withFailMessage("custom error message").isEqualTo(expected);

 

· Comparator는 assertion 후에 작동하지 않음

// 잘못된 사용: Comparator는 assertion 후에 작동하지 않는다
assertThat(actual).isEqualTo(expected).usingComparator(new CustomComparator());

// 올바른 사용
assertThat(actual).usingComparator(new CustomComparator()).isEqualTo("a");

 

컬렉션 테스트하기

 

출처

https://www.baeldung.com/assertj-exception-assertion

https://incheol-jung.gitbook.io/docs/study/undefined-3/d.-assertj

https://joel-costigliola.github.io/assertj/assertj-core.html

https://www.daleseo.com/assertj/

반응형

댓글