JUnit 입문

nona·2021년 5월 29일
0

IntelliJ

목록 보기
3/5

최범균님의 "테스트 주도 개발 시작하기" 도서를 읽으며 TDD 입문을 해 봅니다.
그런데 테스트 요건에 의해 테스트 코드부터 작성하면서 개발하는 방식이 익숙해지려면 많은 시간이 걸릴것 같아요.

(참고) JUnit User Guide

환경

  • 2021년 5월
  • M1 맥미니
  • IntelliJ 2021.1
  • Spring Initializr 데모 프로젝트 생성
    • Gradle Project / Java 11 / Spring Boot 2.5.0 / Dependencies : Spring Web, Spring Boot DevTools
    • JUnit5 (junit-jupiter 5.7.2 의존)

테스트 Class 생성

  • IntelliJ 기준 해당 클래스에서 cmd⌘ + N (Generate) 에서 손쉽게 Test Class 생성 가능
  • 보통 클래스명뒤에 Test 로 작성 (SampleServiceTest.java)

Junit Assertions API

  • (API) Class Assertions
  • 주요 메서드
    • assertEquals() / assertNotEquals()
      • 값이 같은지 다른지 테스트
    • assertSame() / assertNotSame()
      • 객체가 같은지 다른지 테스트
    • assertTrue() / assertFalse()
      • 값 true/false 테스트
    • assertNull() / assertNotNull()
      • 값 Null 테스트
    • fail()
      • 테스트 실패 처리
    • assertAll()
      • 여러 테스트를 테스트
    • assertThrows()
      • 특정 예외 발생 테스트
    • assertTimeout() / assertTimeoutPreemptively()
      • 특정 시간안에 종료되는지 테스트

기본 테스트 작성

  • 기본 테스트코드 작성
package com.example.demo;

import org.junit.jupiter.api.*;

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

class JunitSampleTest {

    /** 테스트 실행 전 실행, static 메서드 */
    @BeforeAll
    static void tBeforeAll() {
        System.out.println("@BeforeAll Method");
    }

    /** 테스트 실행 후 실행, static 메서드 */
    @AfterAll
    static void tAfterAll() {
        System.out.println("@AfterAll Method");
    }

    /** Test 어노테이션이 선언된 메서드 실행 전 매번 실행 */
    @BeforeEach
    void setUp() {
        System.out.println("@BeforeEach Method");
    }

    /** Test 어노테이션이 선언덴 메서드 실행 후 매번 실행 */
    @AfterEach
    void tearDown() {
        System.out.println("@AfterEach Method");
    }

    @DisplayName("일반 테스트1")
    @Test
    void t_테스트1() {
        System.out.println("테스트1");
        assertEquals(1, 2);
    }

    @DisplayName("일반 테스트2")
    @Test
    void t_테스트2() {
        System.out.println("테스트2");
        assertEquals("a", "a");
    }

    @Disabled
    @DisplayName("무시된 테스트")
    @Test
    void t_무시당한_테스트() {
        System.out.println("@Disabled 어노테이션으로 무시된 테스트");
    }

}

테스트 실행

실행 방법

  • IntelliJ 는 테스트 코드의 에디터에 실행버튼이 표시됨 (단축키 shift + ctrl + R)
    • 클래스 전체 또는 메서드단위 실행 가능
  • 콘솔에서 실행
    • ./gradlew test 또는 ./gradlew build 빌드시에도 실행됨
    • 테스트코드 실패시 빌드 실패하므로 테스트 제외하고 빌드하고자 하는 경우 gradle build -x test

실행 결과

  • IntelliJ 테스트 결과

  • 실행 결과 콘솔

> Task :compileJava UP-TO-DATE
> Task :processResources UP-TO-DATE
> Task :classes UP-TO-DATE
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test FAILED
@BeforeAll Method
@BeforeEach Method
테스트1
@AfterEach Method

expected: <1> but was: <2>
Expected :1
Actual   :2
<Click to see difference>

org.opentest4j.AssertionFailedError: expected: <1> but was: <2>
	at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
...(생략:trace)

@BeforeEach Method
테스트2
@AfterEach Method
@AfterAll Method

JunitSampleTest > 일반 테스트1 FAILED
    org.opentest4j.AssertionFailedError at JunitSampleTest.java:37
3 tests completed, 1 failed, 1 skipped
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':test'.
> There were failing tests. See the report at: file:///Users/.../IdeaProjects/demo-springbootweb/build/reports/tests/test/index.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 756ms
4 actionable tasks: 2 executed, 2 up-to-date
profile
개발 놀이 중

0개의 댓글