AssertJ 파헤치기

Sangwoo Park·2022년 11월 5일
0

테스트코드 작성을 공부하다가 AssertJ 에 대해 탐구하게 되었고, AssertJ 깃허브 라이브러리에 있는 examples 디렉토리를 발견했다. 지금까지 isEqualTo(), isTrue(), isNull() 과 같은 간단한 것만 알고 있었는데, 이번 기회에 여러가지 사용법을 살펴보기로 했다.

Chaining

assertThat(frodo.getName())
.isEqualTo("Frodo")
.isNotEqualTo("Frodon");

Matches

assertThat(frodo).matches(p -> p.age > 30 && p.getRace() == HOBBIT);

URI

assertThat(new URI("http://assertj.org:8080/news.html#print"))
.hasHost("assertj.org")
.hasPort(8080)
.hasPath("/news.html")
.hasFragment("print");

assertThat(new URI("http://assertj.org"))
.hasNoFragment()
.hasNoPort()
.hasPath("")
.hasNoQuery()
.hasNoUserInfo();

assertThat(new URI("http://test@www.helloworld.org/index.html")).hasUserInfo("test");

assertThat(new URI("http://www.helloworld.org/index.html?happy=very")).hasParameter("happy");
assertThat(new URI("http://www.helloworld.org/index.html?happy")).hasParameter("happy", null);
assertThat(new URI("http://www.helloworld.org/index.html?happy=very")).hasParameter("happy", "very");
assertThat(new URI("http://www.helloworld.org/index.html?happy=very")).hasNoParameter("happy", null);

String

assertThat("Frodo")
.startsWith("Fro")
.endsWith("do")
.hasSize(5)
.contains("rod")
.doesNotContain("fro")
.doesNotContainIgnoringCase("froo")
.containsOnlyOnce("do")
.isSubstringOf("Frodon")
.doesNotContainAnyWhitespaces();

// using regex
assertThat("Frodo").matches("..o.o").doesNotMatch(".*d");

// check for empty string, or not.
assertThat("").isEmpty();
assertThat("").isNullOrEmpty();
assertThat("not empty").isNotEmpty();

// check size.
assertThat("C-3PO").hasSameSizeAs("R2-D2").hasSize(5);

Predicate

IntPredicate evenNumber = n -> n % 2 == 0;

assertThat(evenNumber).accepts(4)
.rejects(3)
.accepts(2, 4, 6)
.rejects(1, 3, 5);

Optional

Optional<String> optional = Optional.of("Test");

assertThat(optional)
.isPresent()
.containsInstanceOf(String.class)
.contains("Test");

Number

// equals / no equals assertions
assertThat(sam.age)
.isEqualTo(38)
.isCloseTo(40, within(10))
.isEven();

assertThat(frodo.age)
.isEqualTo(33)
.isNotEqualTo(sam.age)
.isOdd();

// <= < > >= assertions
assertThat(sam.age)
.isGreaterThan(frodo.age)
.isGreaterThanOrEqualTo(38);

assertThat(frodo.age)
.isLessThan(sam.age)
.isLessThanOrEqualTo(33);

assertThat(sam.age).isBetween(frodo.age, gimli.age);

// shortcuts for assertions : > 0, < 0 and == 0
assertThat(frodo.age - frodo.age).isZero();
assertThat(frodo.age - sauron.age).isNegative();
assertThat(gandalf.age - frodo.age).isPositive();

assertThat(frodo.age - frodo.age).isNotNegative();
assertThat(frodo.age - frodo.age).isNotPositive();
assertThat(gandalf.age - frodo.age).isNotNegative();
assertThat(frodo.age - sauron.age).isNotPositive();

assertThat(1.0f).isFinite();
assertThat(1.0).isFinite();

Map

assertThat(ringBearers).isNotEmpty().hasSize(4);

// MapEntry.entry(key, value)).
assertThat(ringBearers).contains(entry(oneRing, frodo), entry(nenya, galadriel));
// using java util Map.Entry
assertThat(ringBearers).contains(javaMapEntry(oneRing, frodo), javaMapEntry(nenya, galadriel));
// same assertion but different way of expressing it : no entry call needed but no varargs support.
assertThat(ringBearers).containsEntry(oneRing, frodo).containsEntry(nenya, galadriel);
// opposite of contains/containsEntry
assertThat(ringBearers).doesNotContain(entry(oneRing, sauron), entry(nenya, aragorn));
assertThat(ringBearers).doesNotContainEntry(oneRing, aragorn);

// Assertion on key
assertThat(ringBearers).containsKey(nenya);
assertThat(ringBearers).containsKeys(nenya, narya);
assertThat(ringBearers).containsValues(frodo, galadriel);
assertThat(ringBearers).containsOnlyKeys(nenya, narya, vilya, oneRing);
assertThat(ringBearers).doesNotContainKey(manRing);
assertThat(ringBearers).doesNotContainKeys(manRing, dwarfRing);

// Assertion on value
assertThat(ringBearers).containsValue(frodo);
assertThat(ringBearers).doesNotContainValue(sam);

assertThat(ringBearers).hasSameSizeAs(ringBearers);
assertThat(ringBearers).containsAllEntriesOf(ringBearers);

List

List<Ring> elvesRings = list(vilya, nenya, narya);
assertThat(elvesRings).contains(vilya, atIndex(0))
.contains(nenya, atIndex(1))
.contains(narya, atIndex(2));

assertThat(elvesRings).isSubsetOf(ringsOfPower);

Exceptions

 Exception cause = new Exception("chemical explosion");
 Exception e = new RuntimeException("Boom!", cause);

assertThat(e).isInstanceOf(RuntimeException.class);

assertThat(e)
.hasCause(cause)
.hasCauseReference(cause
.hasCauseInstanceOf(Exception.class);

assertThat(e)
.hasMessage("Boom!")
.hasMessage("%s!", "Boom")
.hasRootCauseMessage("chemical explosion")
.hasRootCauseMessage("chemical %s", "explosion");

assertThat(e)
.hasMessageStartingWith("Boo")
.hasMessageContaining("oom")
.hasMessageContainingAll("Boo", "oom")
.hasMessageNotContainingAny("bar", "foo")
.hasMessageEndingWith("!");

 assertThatExceptionOfType(RuntimeException.class)
 .isThrownBy(() -> {
      throw new RuntimeException(new IllegalArgumentException("cause message"));
    })
    .havingCause()
    .withMessage("cause message");
    
assertThatThrownBy(() -> { throw new IllegalArgumentException("boom!"); })
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("boom");

Class

assertThat(Magical.class).isAnnotation();
assertThat(Ring.class).isNotAnnotation()
.hasAnnotation(Magical.class);

assertThat(TolkienCharacter.class).isPublic
assertThat(String.class).isPublic();
assertThat(MyClass.class).isProtected();
assertThat(MySuperClass.class).isPackagePrivate();

assertThat(MyClass.class)
.hasPublicFields("fieldOne")
.hasPublicFields("fieldOne", "fieldTwo")
.hasPublicFields("fieldTwo", "fieldOne")
.hasDeclaredFields("fieldThree")
.hasDeclaredFields("fieldThree", "fieldTwo", "fieldOne")
.hasOnlyPublicFields("fieldOne", "fieldTwo")
.hasOnlyPublicFields("fieldTwo", "fieldOne")
.hasOnlyDeclaredFields("fieldThree", "fieldTwo", "fieldOne");

ref) AssertJ Github

profile
going up

0개의 댓글