💻AssertJ란
AssertJ는 많은 assertion을 제공하는 자바 라이브러리이다. 오류 메세지와 테스트 코드의 가독성을 높이고 자신이 사용하는 IDE에서 사용하기에 용이하다.
AssertJ는 사이드 프로젝트로 만들어졌다. 만약 무엇인가 잘못된것이 있다면 언제든지 피드백을 할 수 있다고 원작자가 말하였다.
가독성 이야기를 해보자면
//JUnit
assertEquals(expected, actual);
//AssertJ
assertThat(actual).isEqualTo(expected);
두 예제가 있는데 첫번째가 JUnit에서 제공하는 assertEquals이다. 아래는 AssertJ의 AssertThat이다.
AssertThat이 확실히 직관적으로 보이고 가독성이 올라간다.
가장 기본적인 예제
@Test
void simple_case() {
assertThat("ABCD").isNotNull()
.startsWith("A")
.contains("BC")
.endsWith("D");
}
봐도 어느정도는 어떤말인지 감은 온다. "ABCD"라는 문자열이 NULL이 아니고 "A"로 시작하고 "BC"가 포함되어 있고 "D"로 끝난다는 테스트 예제이다.
이제 다양한 예제를 보자
💻Filtering assertions
@Test
void filter_test1(){
List<Human> list = new ArrayList<>();
Human k = new Human("Kim",22);
Human a = new Human("Aim",23);
Human p = new Human("Park",42);
Human j = new Human("Jin",12);
Human y = new Human("yun",32);
list.add(k);
list.add(a);
list.add(p);
list.add(j);
list.add(y);
Assertions.assertThat(list).filteredOn(human ->
human.getName().contains("i"))
.containsOnly(a,j,k);
}
예를 보면 Human클래스에는 이름과 나이가 있다. filteredOn은 직관적으로 걸러낸다?이렇게 생각하면 쉬울것이다.
이름을 모두 가져와서 이름중에 i가 포함되는 이름을 걸러낸다. 그 다음 containOnly로 a,j,k 가 맞는지 검증한다.
💻객체의 property를 검증 예제
@Test
void filter_test2() {
List<Human> list = new ArrayList<>();
Human k = new Human("Kim",22);
Human a = new Human("Aim",23);
Human p = new Human("Park",42);
Human j = new Human("Jin",12);
Human y = new Human("yun",32);
list.add(k);
list.add(a);
list.add(p);
list.add(j);
list.add(y);
Assertions.assertThat(list).
filteredOn("age", 22)
.containsOnly(k);
}
위와 세팅은 같다. assertThat 구문에서 프로퍼티에 값에 접근하여 값을 검증한다.
값이 포함되지 않은 경우도 검증을 할 수 있다.
@Test
void filter_test3() {
List<Human> list = new ArrayList<>();
Human k = new Human("Kim",22);
Human a = new Human("Aim",23);
Human p = new Human("Park",42);
Human j = new Human("Jin",12);
Human y = new Human("yun",32);
list.add(k);
list.add(a);
list.add(p);
list.add(j);
list.add(y);
Assertions.assertThat(list)
.filteredOn("age", notIn(22))
.containsOnly(k);
}
notIn안에 들어간 값이 없는 객체만 검증하는것이다.
나머지로는 In,not등이 있다. not과 notIn은 거의 동일하다.
💻property 추출하기
extracting을 사용하면 테스트를 할때 객체 이름을 검증하기 위해 반복문에서 이름을 꺼내고 또 다른 리스트에 담고 비교하는 불편한 과정을 간편하게 해결할 수 있다.
@Test
void filter_test4() {
List<Human> list = new ArrayList<>();
Human k = new Human("Kim",22);
Human a = new Human("Aim",23);
Human p = new Human("Park",42);
Human j = new Human("Jin",12);
Human y = new Human("yun",32);
list.add(k);
list.add(a);
list.add(p);
list.add(j);
list.add(y);
Assertions.assertThat(list).extracting("name")
.contains("Kim","Aim","Park","Jin","yun");
}
list를 넘겨도 list에서 어떤 함수를 부르고 걸러진 값들에 대한 필드를 추출(extracting)해서 검증할 수 있다.
또, 필드명뿐만 아니라 클래스 타입을 명시하여 검증을 강하게 할 수 있다.
@Test
void filter_test5() {
List<Human> list = new ArrayList<>();
Human k = new Human("Kim",22);
Human a = new Human("Aim",23);
Human p = new Human("Park",42);
Human j = new Human("Jin",12);
Human y = new Human("yun",32);
list.add(k);
list.add(a);
list.add(p);
list.add(j);
list.add(y);
Assertions.assertThat(list).extracting("name",String.class)
.contains("Kim","Aim","Park","Jin","yun");
}
그리고 튜플로도 추출이 가능하다. 여러개의 필드를 검증할 때 유용하다.
@Test
void filter_test6() {
List<Human> list = new ArrayList<>();
Human k = new Human("Kim",22);
Human a = new Human("Aim",23);
Human p = new Human("Park",42);
Human j = new Human("Jin",12);
Human y = new Human("yun",32);
list.add(k);
list.add(a);
list.add(p);
list.add(j);
list.add(y);
Assertions.assertThat(list).extracting("name","age")
.contains(tuple("Kim",22)
,tuple("Aim",23)
,tuple("Park",42)
,tuple("Jin",12)
,tuple("yun",32));
}
💻String assertions
문자열 검증 예시이다.
@Test
void stringAssertions(){
String s = "ABCDE";
Assertions.assertThat(s).startsWith("A").contains("BCD").endsWith("E");
}
💻DBB 스타일
@Test
void DBB_st()throws Exception{
//given
//when
Throwable t = catchThrowable(()-> {
throw new Exception("Exception");
});
//then
Assertions.assertThat(t).isInstanceOf(Exception.class)
.hasMessageContaining("Exception");
}
given.when.then 주석으로 가독성이 높고 순차적으로 어디서 어떤 작업을 하는지 알기 용이하다.
💻Exception test(테스트 예외 처리)
@Test
public void exception_assertion() {
assertThatThrownBy(() -> {
throw new Exception("exception");
}).isInstanceOf(Exception.class)
.hasMessageContaining("exception"); };
assertThatThrownBy()는 Trowable보다 가독성이 높게 작성할 수 있다.
예외 처리 문법 예제
@Test
public void exception_assertion() {
assertThatIOException().isThrownBy(() -> {
throw new IOException("exception");
})
.withMessage("exception")
.withMessageContaining("exception")
.withNoCause();
}
@Test
public void testException() {
assertThatExceptionOfType(IOException.class).isThrownBy(() -> {
throw new IOException("exception");
})
.withMessage("exception")
.withMessageContaining("exception")
.withNoCause();
}
🧑🏻💻예제 코드 : https://github.com/ryudongjae/blog-ex
GitHub - ryudongjae/blog-ex: 📁블로그 예제 코드
📁블로그 예제 코드 . Contribute to ryudongjae/blog-ex development by creating an account on GitHub.
github.com
⌨️REFERENCE
'Dev > TestCode' 카테고리의 다른 글
[TestCode] JUnit5 기본 메뉴얼 (0) | 2021.12.05 |
---|