Hamcrest

seongmin·2022년 11월 16일
0

Spring

목록 보기
35/38
post-thumbnail

Hamcrest

Hamcrest는 JUnit 기반의 단위 테스트에서 사용할 수 있는 Assertion Framework이다.

JUnit에서도 Assertion 을 위한 다양한 메서드를 지원하지만 Hamcrest는 다음과 같은 이유로 JUnit에서 지원하는 Assertion 메서드보다 더 많이 사용된다.

사용하는 이유

  • Assertion을 위한 매쳐(Matcher)가 자연스러운 문장으로 이어지므로 가독성이 향상 된다.
  • 테스트 실패 메시지를 이해하기 쉽다.
  • 다양한 Matcher를 제공한다.

예시

  • JUnit에서의 Assertion
public class HelloJunitTest {
    @DisplayName("Hello Junit Test")
    @Test
    public void assertionTest1() {
        String actual = "Hello, JUnit";
        String expected = "Hello, JUnit";

        assertEquals(expected, actual); // (1)
    }
}
  • Hamcrest에서의 Assertion
public class HelloHamcrestTest {

    @DisplayName("Hello Junit Test using hamcrest")
    @Test
    public void assertionTest1() {
        String expected = "Hello, JUnit";
        String actual = "Hello, JUnit";

        assertThat(actual, is(equalTo(expected)));  // (1)
    }
}
  • assertThat(actual, is(equalTo(expected)));

마치 영어문장과 같이 결과 값(actual)이 기대 값(expected)과 같다는 것을 검증(Assertion)한다. 처럼 해석할 수 있다. 즉, 알아보기가 쉽다.


  • JUnit
public class AssertionNullHamcrestTest {

    @DisplayName("AssertionNull() Test")
    @Test
    public void assertNotNullTest() {
        String currencyName = getCryptoCurrency("ETH");

        assertNotNull(currencyName, "should be not null");
    }

    private String getCryptoCurrency(String unit) {
        return CryptoCurrency.map.get(unit);
    }
}
  • Hamcrest
public class AssertionNullHamcrestTest {

    @DisplayName("AssertionNull() Test")
    @Test
    public void assertNotNullTest() {
        String currencyName = getCryptoCurrency("ETH");

        assertThat(currencyName, is(notNullValue()));   // (1)
//        assertThat(currencyName, is(nullValue()));    // (2)
    }

    private String getCryptoCurrency(String unit) {
        return CryptoCurrency.map.get(unit);
    }
}

(2) 의 주석을 해제하고 실행 시

Expected: is null
     but: was "Ethereum"

기대값은 null 이지만 실제 출력 값은 "Ethereum" 이라는 것을 직관적으로 알 수 있다.

0개의 댓글