성실한 사람이 되자

성실하게 글쓰자

This is spear

Programming/JUnit5

JUnit5 기본적인 사용법

Imaspear 2020. 6. 24. 23:32
728x90

 

JUNIT4 → JUNIT5

JUNIT5에 대한 기본적인 사용법

Guide to JUnit 5 Parameterized Tests

JUnit5 의 장점

이전 버전부터 시작하겠습니다. JUnit 4에는 몇 가지 명확한 제한이 있습니다.

  • 전체 프레임 워크는 단일 jar 라이브러리에 포함되었습니다. 특정 기능 만 필요한 경우에도 전체 라이브러리를 가져와야합니다.

    JUnit 5에서는 더 세분화되어 필요한 것만 가져올 수 있습니다

  • 한 테스트 러너는 한 번에 JUnit 4에서만 테스트를 실행할 수 있습니다.

    (예 : SpringJUnit4ClassRunnerParameterized 또는 Parameterized )

    JUnit 5를 사용하면 여러 주자가 동시에 작업 할 수 있습니다

  • JUnit 4는 Java 8을 넘어선 고급 기능이 없습니다.

    JUnit 5는 Java 8 기능을 잘 활용합니다.

JUnit 5의 기본 개념은 이러한 단점을 대부분 해결하기 위해 JUnit 4를 완전히 다시 작성하는 것이 었습니다.

차이점

JUnit 4는 JUnit 5를 구성하는 모듈로 나뉩니다.

  • JUnit 플랫폼 –

    이 모듈은 테스트 실행, 발견 및 보고에 관심이 있는 모든 확장 프레임 워크를 포괄합니다.

  • JUnit Vintage –

    이 모듈은 JUnit 4 또는 JUnit 3과의 역 호환성을 허용합니다.

Annotations

JUnit 5에는 Annotations 내에서 중요한 변경 사항이 있습니다. 가장 중요한 것은 더 이상 기대 값을 지정 하기 위해 @Test Annotations 을사용할 수 없다는 것입니다.

JUnit 4 의 예상 매개 변수 :

@Test(expected = Exception.class)
public void shouldRaiseAnException() throws Exception {
    // ...
}

이제 assertThrows 메소드를 사용할 수 있습니다 .

public void shouldRaiseAnException() throws Exception {
    Assertions.assertThrows(Exception.class, () -> {
        //...
    });
}

JUnit 4 의 시간 종료 속성

@Test(timeout = 1)
public void shouldFailBecauseTimeout() throws InterruptedException {
    Thread.sleep(10);
}

이제 JUnit 5 의 assertTimeout 메소드 :

@Test
public void shouldFailBecauseTimeout() throws InterruptedException {
    Assertions.assertTimeout(Duration.ofMillis(1), () -> Thread.sleep(10));
}

JUnit 5에서 변경된 다른 주석 :

  • @Before@BeforeEach

    주석이로 이름이 변경됩니다

  • @After.

    주석의 이름이 @AfterEach 로 변경되었습니다

  • @BeforeClass.

    주석의 이름이 @BeforeAll 로 변경되었습니다

  • @AfterClass.

    주석의 이름이 @AfterAll 로 변경되었습니다

  • @.

    주석 무시 는 @Disabled 로 이름이 변경되었습니다

Assertions

이제 JUnit 5에서 람다로 Assertions 메시지를 작성할 수 있으며, 필요할 때 복잡한 메시지 구성을 건너 뛸 수 있습니다.

@Test
public void shouldFailBecauseTheNumbersAreNotEqual_lazyEvaluation() {
    Assertions.assertTrue(
      2 == 3, 
      () -> "Numbers " + 2 + " and " + 3 + " are not equal!");
}

JUnit 5에서 Assertions 을 그룹화 할 수도 있습니다

@Test
public void shouldAssertAllTheGroup() {
    List<Integer> list = Arrays.asList(1, 2, 4);
    Assertions.assertAll("List is not incremental",
        () -> Assertions.assertEquals(list.get(0).intValue(), 1),
        () -> Assertions.assertEquals(list.get(1).intValue(), 2),
        () -> Assertions.assertEquals(list.get(2).intValue(), 3));
}

Assumptions

새로운 Assumptions 클래스는 이제 org.junit.jupiter.api.Assumptions에 있습니다. JUnit 5는 JUnit 4의 기존 assumptions 방법을 완벽하게 지원하며 특정 시나리오에서만 일부 assertions 을 실행할 수 있도록 일련의 새로운 방법을 추가합니다.

@Test
public void whenEnvironmentIsWeb_thenUrlsShouldStartWithHttp() {
    assumingThat("WEB".equals(System.getenv("ENV")),
      () -> {
          assertTrue("http".startsWith(address));
      });
}

Tagging And Filtering

JUnit 4에서는 @Category Annotation 을 사용하여 테스트를 그룹화 할 수 있습니다. JUnit 5에서는 @Category Annotation 이 @Tag Annotation으로 대체됩니다 .

@Tag("annotations")
@Tag("junit5")
@RunWith(JUnitPlatform.class)
public class AnnotationTestExampleTest {
    /*...*/
}

maven-surefire-plugin을 사용하여 특정 태그를 포함 / 제외 할 수 있습니다 .

<build>
    <plugins>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <properties>
                    <includeTags>junit5</includeTags>
                </properties>
            </configuration>
        </plugin>
    </plugins>
</build>

New Annotations for Running Tests

@RunWith은 다른 프레임 워크 테스트 컨텍스트를 통합 또는 JUnit 4의 JUnit 테스트 케이스의 전반적인 실행 흐름을 변경하기 위해 사용되었습니다. JUnit 5에서는 @ExtendWith 주석을 사용하여 유사한 기능을 제공 할 수 있습니다.

예를 들어 JUnit 4의 Spring 기능을 사용하려면 다음을 수행하십시오.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
  {"/app-config.xml", "/test-data-access-config.xml"})
public class SpringExtensionTest {
    /*...*/
}

이제 JUnit 5에서는 간단한 확장입니다.

@ExtendWith(SpringExtension.class)
@ContextConfiguration(
  { "/app-config.xml", "/test-data-access-config.xml" })
public class SpringExtensionTest {
    /*...*/
}

New Test Rules Annotations

JUnit 4에서는 @Rule 및 @ ClassRule 주석을 사용하여 테스트에 특수 기능을 추가했습니다.

JUnit 5에서는 @ExtendWith 주석을 사용하여 동일한 논리를 재현 할 수 있습니다 .

예를 들어, 테스트 전후에 로그 추적을 작성하는 JUnit 4에 사용자 정의 규칙이 있다고 가정하십시오

public class TraceUnitTestRule implements TestRule {
  
    @Override
    public Statement apply(Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                // Before and after an evaluation tracing here 
                ...
            }
        };
    }
}

그리고 테스트를 구현합니다 :

@Rule
public TraceUnitTestRule traceRuleTests = new TraceUnitTestRule();

JUnit 5에서는 훨씬 더 직관적인 방식으로 동일하게 작성할 수 있습니다.

public class TraceUnitExtension implements AfterEachCallback, BeforeEachCallback {
 
    @Override
    public void beforeEach(TestExtensionContext context) throws Exception {
        // ...
    }
 
    @Override
    public void afterEach(TestExtensionContext context) throws Exception {
        // ...
    }
}

org.junit.jupiter.api.extension 패키지에서 사용 가능한 JUnit 5의AfterEachCallback 및 BeforeEachCallback 인터페이스를 사용하여 테스트 규칙을 쉽게 구현합니다.

@RunWith(JUnitPlatform.class)
@ExtendWith(TraceUnitExtension.class)
public class RuleExampleTest {
  
    @Test
    public void whenTracingTests() {
        /*...*/
    }
}

JUnit 5 Vintage

JUnit Vintage는 JUnit 5 컨텍스트 내에서 JUnit 3 또는 JUnit 4 테스트를 실행하여 JUnit 테스트 마이그레이션을 지원합니다.

JUnit Vintage Engine을 가져 와서 사용할 수 있습니다.

<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <version>${junit5.vintage.version}</version>
    <scope>test</scope>
</dependency>

출처

Migrating from JUnit 4 to JUnit 5 | Baeldung

 

Migrating from JUnit 4 to JUnit 5 | Baeldung

Learn how to migrate from JUnit 4 to the latest JUnit 5 release - with an overview of the differences between the two versions.

www.baeldung.com

GitHub

eugenp/tutorials