JUnit 5 Architecture

3개의 모듈로 구성

JUnit5 = JUnit Platform + JUnit Jupiter + Junit Vintage

Platform

Jupiter

Vintage (하위 버전 호환)

Test Instance Lifecycle

기본적으로 각 test class의 각 test method가 실행되기 전에 새로운 인스턴스를 생성함(per-method)

per-class 테스트 인스턴스 생성

Test Class, Test Method

class StandardTests {

    @BeforeAll
    static void initAll() {
    }

    @BeforeEach
    void init() {
    }

    @Test
    void succeedingTest() {
    }

    @Test
    void failingTest() {
        fail("a failing test");
    }

    @Test
    @Disabled("for demonstration purposes")
    void skippedTest() {
        // not executed
    }

    @Test
    void abortedTest() {
        assumeTrue("abc".contains("Z"));
        fail("test should have been aborted");
    }

    @AfterEach
    void tearDown() {
    }

    @AfterAll
    static void tearDownAll() {
    }

}

@Disabled : 클래스와 메서드에 선언 가능, 테스트를 실행하지 않음

Tagging, Filtering

태그는 테스트를 마킹하고 필터링하는 목적으로 사용함

특징

@Tag("oauth2")
@Tag("dev")
class OAuth2DevTest {
    
}

Assertions

Extensions

의존성 주입 Extensions

Junit을 사용해서 의존성 주입을 할 수 있지만 대부분의 경우 외부 Extension 사용

@ExtendWith(Mockito.class)
@ExtendWith(SpringExtension.class)
class MyTest {
 
    @Mock
    private MyService myService;
 
    @Autowired
    private MyRepository myRepository;
 
    @Test
    void test() {
        // ...
    }
} 

With Gradle

// test case를 src/test/java 하위에 두고, gradle test 실행
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter-api:5.7.0')
    testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine:5.7.0')
}

// JUnit Platform enable 
tasks.named('test', Test) {
  useJUnitPlatform()
}

Junit5 Annotation, Composed Annotations

코어 어노테이션 위치 : junit-jupiter-api 모듈의 org.junit.jupiter.api 패키지

Junit5 Annotation 종류

JUnit5 어노테이션은 메타 어노테이션으로 사용 가능 -> 복합 어노테이션으로 재정의

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Tag("fast")
@Test
public @Interface FastTest() {
    
}
@FastTest
void oneTest() {
    
}

Test Execution Order

Tests

Nested Tests

Repeated Tests

Dynamic Tests

Timeout

Conditional Test Execution

Test Interface, Default Method