[kotlin] Hamcrest의 사용자 정의 매처
Hamcrest는 자바용 단언 라이브러리로, JUnit 및 기타 테스트 프레임워크와 함께 사용됩니다.
Hamcrest는 매처(matcher)를 사용하여 자체적인 단언을 작성할 수 있습니다. 그러나 Hamcrest의 기본 매처로는 모든 상황을 다루기에는 부족한 경우가 있습니다. 이런 경우 사용자 정의 매처를 만들어 해결할 수 있습니다.
사용자 정의 매처 만들기
사용자 정의 매처를 만들려면 org.hamcrest.matcher
의 TypeSafeMatcher
클래스를 확장해야 합니다. 이 클래스는 matchesSafely
메서드를 오버라이드하여 새로운 단언을 작성할 수 있게 해줍니다.
import org.hamcrest.Description
import org.hamcrest.TypeSafeMatcher
class CustomMatcher(private val expected: String) : TypeSafeMatcher<String>() {
override fun matchesSafely(item: String): Boolean {
// 원하는 단언을 작성합니다.
return item.contains(expected)
}
override fun describeTo(description: Description) {
description.appendText("문자열이 '$expected'를 포함해야 합니다")
}
override fun describeMismatchSafely(item: String, mismatchDescription: Description) {
mismatchDescription.appendText("실제 문자열: $item")
}
}
위의 예제는 CustomMatcher
라는 사용자 정의 매처를 만드는 방법을 보여줍니다. matchesSafely
메서드에서는 원하는 단언을 작성하고, describeTo
및 describeMismatchSafely
메서드에서는 각각 성공과 실패 시에 보여줄 메시지를 정의합니다.
사용 예제
사용자 정의 매처가 만들어졌으니 이를 어떻게 사용하는지 알아봅시다.
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
class CustomMatcherTest {
@Test
fun testCustomMatcher() {
val input = "Hello, world!"
val customMatcher = CustomMatcher("Hello")
assertThat(input, customMatcher)
}
}
위의 테스트 코드에서는 “Hello”라는 문자열을 포함하는지를 확인하기 위해 CustomMatcher
를 사용하고 있습니다.
이와 같이 사용자 정의 매처를 통해 원하는 조건을 단언할 수 있습니다.
참고문헌:
- Hamcrest 공식 문서: https://github.com/hamcrest/JavaHamcrest