관리 메뉴

민우의 코딩노트

AssertJ 필수 부분 정리 본문

Knowledge/Spring

AssertJ 필수 부분 정리

미미누 2022. 2. 20. 18:23

https://pjh3749.tistory.com/241

 

[AssertJ] JUnit과 같이 쓰기 좋은 AssertJ 필수 부분 정리

AssertJ가 core document를 새로운 github.io로 이전했네요 :) . 본 글은 AssertJ 공식 문서를 핵심 챕터를 선정하여 번역하며 정리한 글 입니다. http://joel-costigliola.github.io/assertj/assertj-core.html A..

pjh3749.tistory.com

출처: 위의 글을 보고 AssertJ의 필수 부분을 정리해보았습니다.


Filtering assertions - iterables나 arrays에 적용되는 filtering

List<Human> list = new ArrayList<>();
Human park = new Human("Park", 25);
Human jack = new Human("Jack", 22);

list.add(park);
list.add(jack);

assertThat(list).assertThat(list).filteredOn(human -> human.getName().contains("a"))
	.containsOnly(park, jack);

assertThat 구문에서 filteredOn을 사용한다.

이름을 가져와서 a 가 포함되어 있는 객체들만 필터링을 하고 그 객체를 검증한다. 

assertThat(list).filteredOn("age", 25).containsOnly(park, lee);

 

assertThat 구문에서 클래스의 프로퍼티(나이)에 접근하여 값을 검증한다.

 

assertThat(list).filteredOn("age", notIn(22)).containsOnly(park, lee);

notIn 함수를 사용하여, age가 22가 아닌 객체를 검증할 수 있음.


프로퍼티를 추출하기

assertThat(list).extracting("name").contains("Kim", "Park", "Lee", "Amy", "Jack");

extracting()을 사용하면 프로퍼티를 쉽게 추출 가능하다.

 

assertThat(list).extracting("name", String.class).contains("Kim", "Park", "Lee", "Amy", "Jack");

하나의 인자를 검증할 때는 클래스를 명시하여 타입 검증을 강하게 할 수 있다.

 

assertThat(list).extracting("name", "age")
				.contains(tuple("Kim", 22)

튜플로도 추출 가능하다. (여러 필드를 한 번에 검증할 때 유용)


(잘못된 사용법 피하기)

as()를 assertion 이전에 부르지 말기

assertThat(actual).as("description").isEqualTo(expected);

 

comparator를 assertion 이전에 불러라

assertThat(actual).usingComparator(new CustomComparator()).isEqualTo("a");

BDD 스타일

bdd스타일은 given, when, then으로 이루어진 스타일

 

Exception 처리 test

 

assertThatThrownBy()

assertThatThrownBy(() -> { throw new Exception("boom!"); }).isInstanceOf(Exception.class)
		.hasMessageContaining("boom");

assertThatThrownBy()는 좀 더 나은 가독성으로 작성할 수 있게 해준다.


자주 쓰이는 예외 처리 syntax

 

  • assertThatNullPointerException
  • assertThatIllegalArgumentException
  • assertThatIllegalStateException
  • assertThatIOException

 

예외를 던지지 않는 경우 처리

assertThatCode(() -> { 
		// code that should throw an exception 
        ... 
	}).doesNotThrowAnyException();