파란하늘의 지식창고
article thumbnail
반응형

소개

시간이 지나면 더 좋은 테스트 코드 작성 방법이 나오겠지만 이 글을 작성하는 현재로선 개인적으로 junit 5와 assertJ를 같이 사용하는 게 좋아 보인다.

junit 5

junit은 java에서 테스트 코드 작성을 위해 많이 쓰이는 라이브러리이다.

Spock, TestNG, Serenity, Selenide, Gauge, Geb, HttpUnit 등 수많은 test framework이 있는데 그중 가장 인기 있는 라이브러리이다.

https://junit.org/junit5/docs/current/user-guide/

assertJ

assertJ는 junit이 제공하는 assert 보다 사용하기 편한 문법을 제공한다.

검증할 값의 class type별 문법을 찾아봐야 하는 junit의 assert에 비해 class type별 응답 처리까지 분기하여 제공해주기 때문에 assertThat에 검증할 값을 넣고 자동 완성되는 관련 검증 method를 사용하기만 하면 된다.

@Test
void test() {
    String a = "test";	// 문자열 값 테스트
    assertThat(a).isEqualTo("test");
    assertThat(a).hasSize(4);
    assertThat(a).isNotEmpty();

    int b = 123;	// 숫자 값 테스트
    assertThat(b).isEqualTo(123);
    assertThat(b).isGreaterThan(122);
    assertThat(b).isNotZero();

    List<String> c = List.of("valueA", "valueB");	// 목록 값 테스트
    assertThat(c).hasSize(2);
    assertThat(c).isNotEmpty();
}

https://assertj.github.io/doc/

maven 설정

Spring Boot를 사용하는 경우

만약 Spring Boot를 사용하고 있다면 다음과 같이 설정하면 된다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

그 밖의 경우

Spring Boot를 사용하지 않는 경우 직접 dependency 설정을 해야 한다.

IDE의 build path add library같이 IDE가 제공해주는 기본 설정으로 사용할 수도 있지만 직접 설정하는 게 여러 사람이 같이 쓰기 좋기 때문에 좋다.

다음과 같이 설정한다.

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.junit</groupId>
            <artifactId>junit-bom</artifactId>
            <version>5.8.2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>3.22.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>

eclipse의 경우 사용하는 jdk compiler를 지정해주어야 대상 테스트 method에서 Run As -> JUnit Test가 활성화된다.

<properties>
    <maven.compiler.target>17</maven.compiler.target>
    <maven.compiler.source>17</maven.compiler.source>
</properties>

반응형
profile

파란하늘의 지식창고

@Bluesky_

내용이 유익했다면 광고 배너를 클릭 해주세요