簡體   English   中英

每次動態測試后如何執行代碼?

[英]How execute code after each dynamic test?

有一個測試:

package com.cdek.qa_auto.config;
import com.cdek.qa_auto.utils.CdekJUnitListener;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;


/***
 *
 */
@SpringBootTest
public class JUnit5Test {
    public JUnit5Test() throws Exception {}

    @BeforeEach
    public void beforeEach() throws Exception {
        Launcher launcher = LauncherFactory.create();
        TestExecutionListener listener = new CdekJUnitListener();
        launcher.registerTestExecutionListeners(listener);
    }

    @TestFactory
    public Stream<DynamicTest> test() throws Exception {
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("12");
        list.add("123");
        list.add("1234");
        list.add("12345");

        return list.stream().map(item -> (
                dynamicTest("test_" + item, () -> {
                    if ("1".equalsIgnoreCase(item)) {
                        System.out.println("fail");
                        fail("fail");
                    } else if ("12".equalsIgnoreCase(item)) {
                        assertTrue(false);
                    } else if ("123".equalsIgnoreCase(item)) {
                        throw new Exception("msg");
                    } else {
                        assertTrue(true);
                    }
                        }
                )));
    }
}

例如,為失敗的測試創建一個屏幕。 導入org.junit.platform.launcher.TestExecutionListener的書面實現。

連接因此通常無法正常工作。 不執行完成。

基礎:JUnit5-Maven-SpringBoot

每次動態測試后如何執行特定代碼?

如《 JUnit 5用戶指南》中所述

動態測試的執行生命周期與標准@Test案例的執行生命周期完全不同。 具體來說,沒有針對單個動態測試的生命周期回調。 這意味着@BeforeEach和@AfterEach方法以及它們相應的擴展回調是為@TestFactory方法執行的,而不是為每個動態測試執行的。 換句話說,如果您在lambda表達式中訪問來自測試實例的字段以進行動態測試,則這些字段將不會由回調方法或由同一@TestFactory方法生成的各個動態測試的執行之間的擴展來重置。

因此,您不能使用@AfterEach方法或“之后”生命周期回調擴展之一(即AfterEachCallbackAfterTestExecutionCallback )。

根據您要在“偵聽器”中嘗試實現的目標,您也許可以在TestExecutionListener完成該任務,但是您不能在測試類中進行注冊。 有關詳細信息,請參見《用戶指南》中的插入自己的測試執行監聽器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM