Spring
[Spring] AssertJ 정리
퉁그리
2022. 1. 4. 01:41
assertj는 자바 테스트에 사용되며, 메소드 체이닝을 통해 테스트코드의 가독성과 편의성을 높여주는 라이브러리다.
Assertion description
assertion이 수행될 때 설명을 추가할 수 있다.
as라는 메소드로 지정할 수 있는데 assertion이 수행되기전에 작성되야한다.
TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, Race.HOBBIT);
assertThat(frodo.getAge()).as("check %s's age", frodo.getName()) .isEqualTo(100);
Filtering assertions
@Test
void filter_test() {
List<Human> list = new ArrayList<>();
Human kim = new Human("Kim", 22);
Human park = new Human("Park", 25);
Human lee = new Human("Lee", 22);
Human amy = new Human("Amy", 25);
Human jack = new Human("Jack", 22);
list.add(kim);
list.add(park);
list.add(lee);
list.add(amy);
list.add(jack);
assertThat(list).filteredOn(human -> human.getName().contains("a"))
.containsOnly(park, jack);
}
a를 포함된 객체를 필터링을 한후 리스트로 비교한다. 대소문자를 구분한다.
객체의 프로퍼티를 검증
@Test
void filter_test2() {
List<Human> list = new ArrayList<>();
Human kim = new Human("Kim", 22);
Human park = new Human("Park", 25);
Human lee = new Human("Lee", 25);
Human amy = new Human("Amy", 22);
Human jack = new Human("Jack", 22);
list.add(kim);
list.add(park);
list.add(lee);
list.add(amy);
list.add(jack);
assertThat(list).filteredOn("age", 25).containsOnly(park, lee);
assertThat(list).filteredOn("age", notIn(22, 23)).containsOnly(park, lee);
assertThat(list).filteredOn("age", not(22)).containsOnly(park, lee);
}
filterdOn함수는 객체의 프로퍼티에 접근해서 검증도 가능하다.
프로퍼티를 추출하기
assertThat(list).extracting("name").contains("Kim", "Park", "Lee", "Amy", "Jack");
assertThat(list).extracting("name", String.class).contains("Kim", "Park", "Lee", "Amy", "Jack");
//doesNotContain도 존재
assertThat(list).extracting("name", "age")
.contains(
tuple("Kim", 22),
tuple("Park", 25),
tuple("Lee", 25),
tuple("Amy", 22),
tuple("Jack",22)
);
//tuple로도 가능
객체의 프로퍼티를 추출해서 비교할 수도 있다.
String assertions
@Test
void 문자열_검증() {
String expression = "This is a string";
assertThat(expression).startsWith("This").endsWith("string").contains("a");
}
string의 경우 이렇게 시작부분 끝부분 포함을 설정해줄수있다.
Exception 처리 test
@Test
public void exception_assertion_example() {
String name = Sonataaaaa;
assertThatThrownBy(() -> new Car(name))
.isInstanceOf(Exception.class)
.hasMessageContaining("이름 길이가 5이하여야 합니다.");
};
예외처리의 경우 예외처리 클래스와 메세지를 확인해볼 수 있다.
객체 비교
//isSameAs => 주소값 비교. 메모리 상에서 같은 객체를 참조하는지 확인
assertThat(a).isSameAs(b);
//isEqualTo => 값 비교. 객체가 서로 같은 값을 가지고 있는지 확인
assertThat(a).isEqualTo(b);
출처 :