티스토리 뷰

728x90
반응형

지난 글에선 JUnit을 이용해 비즈니스 로직에 단위 테스트를 적용했다.

 

2022.09.07 - [개발/Spring] - [Spring]JUnit을 이용한 비즈니스 로직 단위 테스트

 

[Spring]JUnit을 이용한 비즈니스 로직 단위테스트

지난 글에선 테스트의 종류와 단위 테스트, JUnit 없는 단위 테스트 구현을 살펴보았다. 2022.09.07 - [개발/Spring] - [Spring]단위 테스트(Unit Test) [Spring]단위 테스트(Unit Test) 지난 글까진 만들어진 애..

gnidinger.tistory.com

다시 언급하자면 JUnit이란 스프링의 테스팅 프레임워크중 하나로, 가장 많은 사용자 수를 자랑한다.

 

오늘 알아볼 Hamcrest는 JUnit에서 사용되는 Assertion 라이브러리 중 하나이다.

 

JUnit에서 지원하는 Assertion 메서드보다 많이 사용되며

 

특히 테스트 표현식을 조금 더 자연스러운 문장이 되도록 도와주는데,

 

Assertion의 Matcher에 특화된 라이브러리라고 할 수 있다.

 

오죽하면 Hamcrest라는 이름 자체가 Matchers의 애너그램이다.

 

아무튼 이 글에서 주로 사용할 클래스는 위 그림에 등장하는 MatchersMatcherAssert이다.

 

하나씩 사용해보며 장점을 알아보자.

 

JUnit Assertion → Hamcrest Assertion

 

Example 1

 

import static org.junit.jupiter.api.Assertions.assertEquals;

public class HelloJunitTest {

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

        assertEquals(expected, actual);
    }
}

위 코드는 이전 글에서 JUnit의 Assertion 메서드로 작성한 검증 클래스이다.

 

assertEquals(expected, actual)메서드를 사용한 것을 볼 수 있다.

 

같은 테스트를 Hamcrest를 이용해서 작성해보자.

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 assertionTest() {
        String actual = "Hello, JUnit";
        String expected = "Hello, World";

        assertThat(actual, is(equalTo(expected)));
    }
}

검증 메서드가 조금 더 문장에 가깝도록(assert That actual is equal To expected) 쓰인 것을 확인할 수 있다.

 

직관적으로 메서드가 어떤 역할을 하는지 알아보기 쉬워졌다.

 

나란히 놓고 보면 확실히 가독성이 좋아진 것을 볼 수 있다.

 

계속해서 에러 메시지를 확인해 보자.

 

오른쪽이 Hamcrest를 적용한 결과이다.

 

역시 문장이 조금 더 매끄러워졌다.

 

Example 2

 

계속해서 지난 글에서 작성한 코드에 Hamcrest를 적용해보자.

import static org.junit.jupiter.api.Assertions.assertNotNull;

public class AssertionNotNullTest {

    @DisplayName("AssertionNotNull() 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);
    }
}

위의 코드는 JUnit에서 지원하는 Assertion 메서드를 이용한 검증 코드이다.

 

검증 대상이 null이 아니기를 기대하고 있다.

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

public class AssertionNullHamcrestTest {

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

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

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

 

같은 로직을 Hamcrest를 이용해 구현했다.

 

 

Example 3

 

import static org.junit.jupiter.api.Assertions.assertThrows;

public class AssertionExceptionTest {

    @DisplayName("throws NullPointerException when map.get()")
    @Test
    public void assertionThrowExceptionTest() {
        assertThrows(NullPointerException.class, () -> getCryptoCurrency("XRP"));
    }

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

NullPointerException이 발생했을 때 던져지는 예외의 발생 여부를 검증하는 로직이다.

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class AssertionExceptionHamcrestTest {

    @DisplayName("throws NullPointerException when map.get()")
    @Test
    public void assertionThrowExceptionTest() {
        Throwable actualException = assertThrows(NullPointerException.class, () -> getCryptoCurrency("XRP"));

        assertThat(actualException.getCause(), is(equalTo(null)));
    }

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

예외에 대한 테스트는 Hamcrest만으로 구현하기 힘들어서 JUnit의 assertThrows() 메서드를 사용한다.

 

리턴 값을 Hamcrest로 검증하는 코드이다.

assertThat(actualException.getCause(), is(equalTo(null)));

와 같이 직관적인 표현으로 교체된 것을 확인할 수 있다.

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함