Spring MVC - Testing part 2
3.Hamcrest를 사용한 Assertion |
-Hamcrest는 JUnit 기반의 단위 테스트에서 사용할 수 있는 Assertion Framework
-아래와 같은 이유로 JUnit에서 지원하는 Assertion 메서드보다 더 많이 사용됨
(1)Assertion을 위한 매쳐(Matcher)가 자연스러운 문장으로 이어지므로 가독성이 향상됨
(2)테스트 실패 메시지를 이해하기 쉬움
(3)다양한 Matcher를 제공함
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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); // (1)
assertThat(actual, is(equalTo(expected))); // (2)
}
}
|
cs |
● (1)assertEquals(expected, actual); <JUnit Assertion 기능 이용>
○ 파라미터로 입력된 값의 변수 이름을 통해 대략적으로 어떤 검증을 하려는지 알 수 있으나 구체적인 의미는 유추를 하는 과정이 필요함
● (2)assertThat(actual, is(equalTo(expected))); <Hamcrest의 매쳐(Matcher) 이용>
○ (2)의 Assertion 코드 한 줄은 ‘assert that actual is equal to expected’라는 하나의 영어 문장으로 자연스럽게 읽혀짐
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class HelloJunitTest {
@DisplayName("Hello Junit Test")
@Test
public void assertionTest1() {
String actual = "Hello, JUnit";
String expected = "Hello, World";
assertEquals(expected, actual); // (3)
assertThat(actual, is(equalTo(expected))); // (4)
}
}
|
cs |
● (3)과 (4)의 테스트 케이스 실행 결과는 "failed"이지만 출력되는 메시지가 다름
● (3)의 실행 결과 메시지
1
2
3
|
expected: <Hello, World> but was: <Hello, JUnit>
Expected :Hello, World
Actual :Hello, JUnit
|
cs |
● (4)의 실행 결과 메시지
1
2
|
Expected: is "Hello, World"
but: was "Hello, JUnit"
|
cs |
*이처럼 Hemcrest의 Matcher를 사용해서 사람이 읽기 편한 자연스러운 Assertion 문장을 구성할 수 있으며, 실행 결과가 “failed”일 경우 역시 자연스러운 “failed” 메시지를 확인할 수 있기때문에 가독성이 높아짐
-내용 출처 : code states