[kotlin] Hamcrest 라이브러리 기능

Hamcrest는 단언문(assertion)이나 검증(validation) 시 실패한 경우 더욱 유용한 기능을 제공하는 자바 라이브러리임. 이번 글에서는 Hamcrest의 여러 가지 기능에 대해 알아보겠습니다.

1. Matcher

Hamcrest의 가장 중요한 기능 중 하나는 Matcher 인터페이스이다. Matcher를 사용하면 테스트 코드를 보다 읽기 쉽고 유지보수하기 쉽게 만들 수 있다. Kotlin에서 Matcher를 사용하는 예제를 살펴보자.

import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.*

fun main() {
    val number = 10
    assertThat(number, `is`(equalTo(10)))
    assertThat(number, `is`(not(equalTo(5))))
}

위 코드에서 MatcherAssert.assertThat을 사용해 테스트 코드를 작성할 수 있다. Matchers 클래스를 이용해 다양한 Matcher를 쉽게 생성할 수 있으며, is, equalTo, not 등의 Matcher를 이용해 간편하게 테스트할 수 있다.

2. 커스텀 Matcher 추가

Hamcrest는 개발자들이 직접 Matcher를 작성하여 추가할 수 있는 확장 기능을 제공함. 다음은 커스텀 Matcher를 작성한 예제이다.

import org.hamcrest.BaseMatcher
import org.hamcrest.Description
import org.hamcrest.Factory
import org.hamcrest.Matcher

class IsEven : BaseMatcher<Int>() {
    override fun describeTo(description: Description?) {
        description?.appendText("짝수여야 함")
    }

    override fun matches(item: Any?): Boolean {
        return (item as Int) % 2 == 0
    }
}

object IsEvenMatcher {
    @Factory
    fun isEven(): Matcher<Int> {
        return IsEven()
    }
}

fun main() {
    val number = 10
    assertThat(number, IsEvenMatcher.isEven())
}

위 예제에서는 BaseMatcher 클래스를 상속받아 짝수를 검증하는 IsEven Matcher를 작성하였다. 또한 Factory 어노테이션을 사용하여 IsEvenMatcher 객체를 생성하였다. 이렇게 작성된 Matcher는 테스트 코드에서 쉽게 활용할 수 있다.

3. 객체 구조 검증

Hamcrest는 객체의 구조를 검증하기 위한 다양한 Matcher를 제공함. 다음은 객체 구조를 검증하는 Matcher를 이용하는 예제이다.

import org.hamcrest.beans.HasProperty

fun main() {
    data class Person(val name: String, val age: Int)

    val person = Person("John", 30)
    assertThat(person, hasProperty("name"))
    assertThat(person, hasProperty("age"))
}

위 코드에서 hasProperty Matcher를 사용하여 Person 객체의 속성을 검증하는 예제를 살펴보았다.

마치며

Hamcrest 라이브러리를 사용하면 테스트 코드를 더욱 가독성 좋고 유지보수하기 쉽게 만들 수 있으며, 커스텀 Matcher를 작성하여 테스트의 다양한 상황을 대응할 수 있다. Hamcrest 라이브러리에 대해 더 알고 싶다면 공식 문서를 참고해보세요.