자바 라이브 스터디 #4 JUnit 5 사용법 : IntelliJ에서 Gradle 프로젝트에 설정하기
JUnit 5
JUnit은 자바에서 사용하는 단위 테스트 프레임워크이며 JUnit 5는 이전 JUnit 버전들과 다르게 다양한 모듈로 구성되어 있습니다.
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
Packt, Introduction to JUnit 5,
subscription.packtpub.com/book/application_development/9781787284661/4/ch04lvl1sec35/introduction-to-junit-5
Introduction to JUnit 5 - Building Web Apps with Spring 5 and Angular 4
In this section, you will learn about JUnit 5 fundamentals, including some of the following:Architectural building blocks of JUnit 5How to get set up with JUnit
subscription.packtpub.com
1. JUnit Platform
JVM에서 테스팅 프레임워크를 시작하는 것에 대한 전반적인 것들을 제공합니다. 테스팅 프레임워크를 개발하기 위한 TestEngine API를 정의하며, 커맨드 라인으로부터 플랫폼을 시작하기 위한 Console Launcher 또한 제공합니다.
2. JUnit Jupiter
JUnit Jupiter 모듈은 JUnit 5에서 테스트를 작성하기 위한 새로운 프로그래밍 모델과 확장 모델을 포함하고 있습니다.
3. JUnit Vintage
JUnit 5 플랫폼에서 JUnit 3과 JUnit 4를 기반으로 하는 테스트를 작동시키기 위한 테스트 엔진을 제공합니다.
JUnit 5 에서 사용하는 어노테이션에 대한 자세한 설명은 JUnit 홈페이지에서 확인할 수 있습니다.
JUnit 5, JUnit 5 User Guide,
junit.org/junit5/docs/current/user-guide/#writing-tests-annotations
다음으로는 IntelliJ에서 Gradle 프로젝트에서 JUnit 5를 사용하도록 설정하는 방법에 대해 알아보겠습니다.
JUnit 5에 대한 의존성을 추가하기 위해 build.gradle 파일 내 Alt + Insert(Windows 기준)로 Junit을 검색하여 org.junit.jupiter:junit-jupiter를 클릭한 후 사용하려는 버전을 골라 의존성을 추가한 후에 Reload하면 junit-jupiter 의존성들이 외부 라이브러리 폴더에 포함되어 있는 것을 확인할 수 있습니다.
의존성을 확인한 후 JUnit 5를 사용하기 위해서는 테스트를 수행할 때 JUnit 플랫폼을 사용하겠다고 설정하는 작업이 필요하며 해당 작업 또한 build.gradle 파일의 test 섹션 내에 useJUnitPlatform()를 추가해주면 됩니다.
이제 JUnit 5로 테스트를 하기 위한 설정은 끝났으며 계산기 예제를 통해 동작하는 방식을 살펴보도록 하겠습니다.
// Calculator.java
package com.teamoddo.demo.junit5;
public class Calculator {
public int add(int a, int b) {
return a+b;
}
}
// CalculatorTests.java
import com.teamoddo.demo.junit5.Calculator;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CalculatorTests {
@Test
@DisplayName("1 + 1 = 2")
void addsTwoNumbers() {
Calculator calculator = new Calculator();
assertEquals(2, calculator.add(1,1), "1 + 1 should equal 2");
}
@ParameterizedTest(name = "{0} + {1} = {2}")
@CsvSource({
"0, 1, 1",
"1, 2, 3",
"49, 51, 100",
"1, 100, 101"
})
void add(int first, int second, int expectedResult) {
Calculator calculator = new Calculator();
assertEquals(expectedResult, calculator.add(first, second),
() -> first + " + " + second + " should equal " + expectedResult);
}
}
@Test 어노테이션으로 테스트라는 것을 명시한 후에 테스트를 실행하면 테스트 정상 수행 여부를 콘솔을 통해 확인하실 수 있습니다.