Hamcrest는 Junit 기반의 소프트웨어 테스트 작성 지원 프레임워크입니다. 다양한 Matcher를 제공하여 간결하고 가독성 있는 코드로 테스트할 수 있게 지원합니다.
- Hamcrest는 다음과 같은 이유로 Junit에 지원하는 Assertion 메서드 보다 최근 더 많이 사용됩니다.
- Assertion을 위한 매쳐(Matcher)가 자연스러운 문장으로 이어지므로 가독성이 향상 된다.
- 테스트 실패 메시지를 이해하기 쉽다.
- 다양한 Matcher를 제공한다.
이해를 돕기위해 이미 Junit Assertion로 작성된 코드를 Hancrest 방식으로 변환하며 설명하겠습니다.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class JunitTest {
@Test
public void assertionTest() {
String actual = "Hello";
String expected = "Hello";
assertEquals(expected, actual);
}
}
위 코드에 대해 간략하게 설명하자면 assertEquals() 메소드를 통해 expected와 actual의 값이 같은지 비교하였습니다. 둘의 값이 같기 때문에 결과는 "passed"가 출력되었습니다.
이제 해당 코드를 Hamcrest 방식으로 변환해 보겠습니다.
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 HamcrestTest {
@Test
public void assertionTest() {
String expected = "Hello, World";
String actual = "Hello, JUnit";
assertThat(actual, is(not(equalTo(expected)))); //변화 부분
}
}
결과 먼저 말씀드리자면 위 코드도 "passed"가 출력됩니다. 해당 코드에서는 Hamcrest의 is(), equalTo() Matcher를 사용했습니다.
맨 아래쪽에 있는 변화 부분을 보시면, assert that actual is not equal to expected’라는 하나의 영어 문장으로 자연스럽게 읽혀집니다.
- 굳이 한글로 번역하자면, ‘결과 값(actual)이 기대 값(expected)과 같지 않다는 것을 검증(Assertion)한다.’ 정도로 해석할 수 있습니다.
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 HamcrestTest {
@Test
public void assertionTest() {
String expected = "Hello, World";
String actual = "Hello, JUnit";
assertThat(actual, is(equalTo(expected))); //변화 부분
}
}
만약 여기서 not() 뺀다면 "falied"가 발생할 것입니다.
[결과]
Expected: is "Hello, World"
but: was "Hello, JUnit"
예시를 한가지 더 들어보겠습니다.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class HamcrestTest {
@Test
public void assertNotNullTest() {
String currencyName = "ETH";
assertNotNull(currencyName, "should be not null");
}
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class HamcrestTest {
@Test
public void assertNotNullTest() {
String currencyName = "ETH";
assertThat(currencyName, is(notNullValue())); // 변화 부분
}
위 코드와 아래 코드의 차이점이 보이시나요? 위 코드는 Assertion 방식으로 아래는 Hamcrest 방식으로 테스팅을 진행한 것입니다.
Hamcrest를 사용해서 Not Null 테스트를 하기위해서는 변화 부분과 같이 Hamcrest의 `is()`, `notNullValue()` 매쳐를 함께 사용할 수 있습니다.
‘currencyName is not Null Value.’와 같이 가독성 좋은 하나의 문장처럼 구성이 되는 것을 볼 수 있습니다.
'JAVA > Test' 카테고리의 다른 글
[자바 Spring] 단위 테스트, 슬라이스 테스트 등 테스트의 기초에 대해 알아보자 (0) | 2022.07.17 |
---|---|
[Spring 자바] Junit 테스트 순서 지정하는 방법 (1) | 2022.07.14 |