Hamcrest는 JUnit 기반의 단위 테스트에서 사용할 수 있는 Assertion Framework입니다.
장점
1. Assertion을 위한 매쳐(Matcher)가 자연스러운 문장으로 이어지므로 가독성이 향상된다.
2. 테스트 실패 메시지를 이해하기 쉽다.
3. 다양한 Matcher를 제공한다
예시 1
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
public class HelloHamcrestTest {
@DisplayName("Hello Junit Test using hamcrest")
@Test
public void assertionTest1() {
String expected = "Hello, JUnit";
String actual = "Hello, JUnit";
//assertEquals(expected, actual);
assertThat(actual, is(equalTo(expected)));
}
}
assertThat()의 첫 번째 파라미터는 테스트 대상의 실제 결과 값입니다.
두 번째 파라미터는 기대하는 값입니다. 즉, 이런 값일 거라고 기대(예상)하는 값입니다.
예시 2
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class AssertionNullHamcrestTest {
@DisplayName("AssertionNull() Test")
@Test
public void assertNotNullTest() {
String currencyName = getCryptoCurrency("ETH");
//assertNotNull(currencyName, "should be not null");
assertThat(currencyName, is(notNullValue()));
assertThat(currencyName, is(nullValue()));
}
private String getCryptoCurrency(String unit) {
return CryptoCurrency.map.get(unit);
}
}
Not Null이나 Null 테스트를 하기 위해서는 위와 같이 Hamcrest의 is()
, notNullValue()
나 NullValue()
매쳐를 함께 사용할 수 있습니다.
예시3
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class AssertionExceptionHamcrestTest {
@DisplayName("throws NullPointerException when map.get()")
@Test
public void assertionThrowExceptionTest() {
Throwable actualException = assertThrows(NullPointerException.class,
() -> getCryptoCurrency("XRP"));
assertThat(actualException.getClass(), is(NullPointerException.class));
}
private String getCryptoCurrency(String unit) {
return CryptoCurrency.map.get(unit).toUpperCase();
}
}