Readability가 뛰어난 Assert 구문을 작성하는게 좋다는 건 모두 가 잘 알고 있는 이야기일 것이다.
assertEquals(expect, actual);
형식은 사용 방법부터 비직관적이라고 많은 사람들이 얘기하고 있다.
Hamcrest도 충분히 직관적이라고 생각하고 뛰어난 표현력과 유연한 notation, informative한 에러 메시지와 같이 assertEquals에 비해서 정말 뛰어나다고 생각을 하고 있었다.
public class BiscuitTest extends TestCase {
public void testEquals() {
Biscuit theBiscuit = new Biscuit("Ginger");
Biscuit myBiscuit = new Biscuit("Ginger");
assertThat(theBiscuit, equalTo(myBiscuit));
}
}
이런 assertThat equalTo같은 표현들이 hamcrest의 표현이다.
equalTo 외에도
A tour of common matchers
Hamcrest comes with a library of useful matchers. Here are some of the most important ones.
- Core
- anything - always matches, useful if you don't care what the object under test is
- describedAs - decorator to adding custom failure description
- is - decorator to improve readability - see "Sugar", below
- Logical
- allOf - matches if all matchers match, short circuits (like Java &&)
- anyOf - matches if any matchers match, short circuits (like Java ||)
- not - matches if the wrapped matcher doesn't match and vice versa
- Object
- equalTo - test object equality using Object.equals
- hasToString - test Object.toString
- instanceOf, isCompatibleType - test type
- notNullValue, nullValue - test for null
- sameInstance - test object identity
- Beans
- hasProperty - test JavaBeans properties
- Collections
- array - test an array's elements against an array of matchers
- hasEntry, hasKey, hasValue - test a map contains an entry, key or value
- hasItem, hasItems - test a collection contains elements
- hasItemInArray - test an array contains an element
- Number
- closeTo - test floating point values are close to a given value
- greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo - test ordering
- Text
- equalToIgnoringCase - test string equality ignoring case
- equalToIgnoringWhiteSpace - test string equality ignoring differences in runs of whitespace
- containsString, endsWith, startsWith - test string matching
요런 많은 Matcher들을 제공하고 있어서 다양한 표현들을 할 수 있다.
여기서 표현이 부족하다면 커스텀 Matcher를 생성할 수도 있고 말이다.
public class IsNotANumber extends TypeSafeMatcher<Double> {
@Override
public boolean matchesSafely(Double number) {
return number.isNaN();
}
public void describeTo(Description description) {
description.appendText("not a number");
}
@Factory
public static <T> Matcher<Double> notANumber() {
return new IsNotANumber();
}
}
난 이게 현재까지는 끝판왕이라고 생각하고 있었다.
이렇게 뛰어난 표현을 하고 에러메시지를 내 입맛에 맞게 정의할 수 있다는데에 너무 만족을 해서
무언가 새로운 더 좋은 방법이 있을 것이라는 생각을 안해봤다는 말이 맞을 것이다.
헌데 얼마 전에 Fest-Assertion이라는 친구를 공유받았다.
아니, 엄밀히 말하면 나는 Fest Assertion이 포함되어 있는 코드를 보게 되었고, 그 코드를 보면서
"우와 이런 표현이라니 !!" 하면서 화들짝 놀랐다 진심으로....
<절단신공!>
일을 해야함으로 오늘은 여기서 끊고 ! Fest Assertion에 대한 소개는 다음으로 미루겠음!




최근 덧글