首页 > 解决方案 > 未执行测试 - JUnit 5 以编程方式 + mvn exec

问题描述

我正在一个 Selenium 自动化项目中运行回归测试。测试是用 JUnit 5.5.1 编写的。没有 Surefire 或 Failsafe 插件(测试不在 src/test/java 下,它们位于 src/main/java 下,因为不是单元测试)。

问题是当我使用 .bat 文件(执行 mvn exec:java ...)运行代码时,没有执行任何测试,我不确定我的配置是否完全正确。在最坏的情况下,这是我正在使用的 JUnit 版本的错误(我从 1 周开始就在使用 JUnit 5,所以我还不熟悉某些配置)。我非常感谢在 JUnit 5 方面比我更有经验的人的帮助。

这就是我执行 .bat 文件后得到的结果。.bat 文件包含以下内容:

mvn clean install exec:java -Dexec.args="'%some_env_as_arg_1%' '%some_env_as_arg_2%'" -DsomeExpectedEnv=%someExpectedEnv%

[INFO] Scanning for projects...
[INFO]
[INFO] -----------------< com.surecomp.doka:doka_automation >------------------
[INFO] Building doka_automation 1.0.1
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ doka_automation ---
[INFO] Deleting C:\Automation\surecomp-automation-doka\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ doka_automation ---
[INFO] Using 'ISO-8859-1' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO] Copying 13 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ doka_automation ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 13 source files to C:\Automation\surecomp-automation-doka\target\classes
[WARNING] No processor claimed any of these annotations: org.junit.jupiter.api.TestMethodOrder,org.springframework.beans.factory.annotation.Autowired,org.springframework.context.annotation.PropertySource,org.junit.jupiter.api.Order,org.springframework.context.annotation.ComponentScan,org.junit.jupiter.api.DisplayName,org.springframework.context.annotation.Configuration,org.junit.jupiter.api.Test,org.springframework.stereotype.Component,org.junit.jupiter.api.TestInstance,org.junit.jupiter.api.extension.ExtendWith,org.junit.jupiter.api.extension.RegisterExtension,com.surecomp.automation.doka.testcases.IntegrationTest,org.springframework.test.context.ContextConfiguration,javax.annotation.PostConstruct,org.springframework.context.annotation.Lazy,org.springframework.context.annotation.Bean,org.junit.jupiter.api.Tag,org.openqa.selenium.support.FindBy
[WARNING] /C:/Automation/surecomp-automation-doka/src/main/java/com/surecomp/automation/doka/exceptions/DOKAAutomationException.java:[8,8] serializable class com.surecomp.automation.doka.exceptions.DOKAAutomationException has no definition of serialVersionUID
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ doka_automation ---
[INFO] Using 'ISO-8859-1' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Automation\surecomp-automation-doka\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ doka_automation ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ doka_automation ---
[INFO] No tests to run.
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ doka_automation ---
[INFO] Building jar: C:\Automation\surecomp-automation-doka\target\doka_automation-1.0.1.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @ doka_automation ---
[INFO] Installing C:\Automation\surecomp-automation-doka\target\doka_automation-1.0.1.jar to C:\Users\alvarot\.m2\repository\com\surecomp\doka\doka_automation\1.0.1\doka_automation-1.0.1.jar
[INFO] Installing C:\Automation\surecomp-automation-doka\pom.xml to C:\Users\alvarot\.m2\repository\com\surecomp\doka\doka_automation\1.0.1\doka_automation-1.0.1.pom
[INFO]
[INFO] >>> exec-maven-plugin:1.2.1:java (default-cli) > validate @ doka_automation >>>
[INFO]
[INFO] <<< exec-maven-plugin:1.2.1:java (default-cli) < validate @ doka_automation <<<
[INFO]
[INFO]
[INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ doka_automation ---
[27/08/2019 03:56:30.841] [ INFO] [TestsRunner.evaluateArgs:60] - -- evaluateArgs started --
[27/08/2019 03:56:30.854] [ INFO] [TestsRunner.evaluateArgs:65] - System propertie work.directory setted as: C:\Automation\Doka Work Directory
[27/08/2019 03:56:30.855] [ INFO] [TestsRunner.evaluateArgs:68] - System propertie selenium.driver.directory setted as: C:\Automation\surecomp-automation-config\drivers
[27/08/2019 03:56:30.856] [ INFO] [TestsRunner.evaluateArgs:69] - -- evaluateArgs finished --
[27/08/2019 03:56:30.859] [ INFO] [TestsRunner.readTestCasesFromCSVFile:97] - -- Reading of CSV file started --
[27/08/2019 03:56:30.860] [ INFO] [TestsRunner.readTestCasesFromCSVFile:98] - CSV file to read: C:\Automation\Doka Work Directory\cases.csv
[27/08/2019 03:56:30.862] [ INFO] [TestsRunner.readTestCasesFromCSVFile:120] - -- Reading of CSV file finished --
[27/08/2019 03:56:30.865] [ INFO] [TestsRunner.loadTestCases:84] - -- Test cases loading started --
[27/08/2019 03:56:31.599] [ INFO] [WebDriverUtils.getWebDriver:26] - Setting WebDriver as first time
Starting ChromeDriver 76.0.3809.68 (420c9498db8ce8fcd190a954d51297672c1515d5-refs/branch-heads/3809@{#864}) on port 38308
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
ago 27, 2019 3:56:35 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
[27/08/2019 03:56:35.498] [ INFO] [TestsRunner.loadTestCases:90] - Test case LoginITCase added to the test execution list.
[27/08/2019 03:56:35.506] [ INFO] [TestsRunner.loadTestCases:93] - -- Test cases loading finished --
[27/08/2019 03:56:35.514] [ INFO] [TestsRunner.runTestProgramaticallyInJUnit5:73] - -- Execution of test LoginITCase started --
[27/08/2019 03:56:36.089] [ INFO] [TestsRunner.runTestProgramaticallyInJUnit5:80] - -- Execution of test LoginITCase finished --

Test run finished after 332 ms
[         2 containers found      ]
[         0 containers skipped    ]
[         2 containers started    ]
[         0 containers aborted    ]
[         1 containers successful ]
[         1 containers failed     ]
[         2 tests found           ]
[         0 tests skipped         ]
[         0 tests started         ]
[         0 tests aborted         ]
[         0 tests successful      ]
[         0 tests failed          ]

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  10.925 s
[INFO] Finished at: 2019-08-27T03:56:36-03:00
[INFO] ------------------------------------------------------------------------
Compilation process finished sucessful.
Press any key to continue . . .

这是我的 pom.xml 配置,用于获取我需要的 JUnit Jupiter 库:

    <properties>
        <java.version>1.8</java.version>
        <spring.version>5.1.3.RELEASE</spring.version>
        <junit-platform.version>1.5.1</junit-platform.version>
        <junit-jupiter.version>5.5.1</junit-jupiter.version>
    </properties>
    <dependencies>
        ...

        <!-- Tests dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <version>${junit-platform.version}</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>${junit-jupiter.version}</version>
        </dependency>
        ...
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>${automation-config-directory}</directory>
                <filtering>false</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>com.surecomp.automation.doka.TestsRunner</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
...

使用 junit-plattform-launcher lib 以编程方式执行测试:

public static void main(String[] args) {
    try {
        evaluateArgs(args);
        String csvFilePath = SetupProps.getCsvFilename();
        //This will take each of test case defined in CSV file as an String array
        String[] testCasesIDs = readTestCasesFromCSVFile(csvFilePath);

        //For each one of the test cases ID finded, will be instantiate its own Test Case class
        loadTestCases(testCasesIDs);

        //Starts the execution of each test case
        SummaryGeneratingListener listener = new SummaryGeneratingListener();

        for (AbstractITCase testCase : testCasesList) {
            runTestProgramaticallyInJUnit5(listener, testCase);
        }
        TestExecutionSummary summary = listener.getSummary();
        summary.printTo(new PrintWriter(System.out));
    } catch (DOKAAutomationException e) {
        LOGGER.error("Error catched. Process aborted.", e);
    } catch (Exception e) {
        LOGGER.error("Unexpected error catched in application. Process aborted.", e);
    }
}


private static void runTestProgramaticallyInJUnit5(SummaryGeneratingListener listener, AbstractITCase testCase) {
    LOGGER.info("-- Execution of test {} started --", testCase.getClass().getSimpleName());
    LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
            .selectors(DiscoverySelectors.selectClass(testCase.getClass())).build();
    Launcher launcher = LauncherFactory.create();
    TestPlan testPlan = launcher.discover(request);
    launcher.registerTestExecutionListeners(listener);
    launcher.execute(request);
    LOGGER.info("-- Execution of test {} finished --", testCase.getClass().getSimpleName());
}

所有测试类的超级类:

@ExtendWith(SpringExtension.class)
@IntegrationTest
@ContextConfiguration(classes = {AppConfig.class})
public abstract class AbstractITCase {
@RegisterExtension
protected static ReporterHandlerExtension runnerExtension = new ReporterHandlerExtension
        .Builder()
        .reports(extent)
        .driver(WebDriverUtils.getWebDriver())
        .build();

static {...}

@Autowired
protected WebDriver driver;
}

登录测试类:

@PropertySource("classpath:test_values/login/login_ok_values.properties")
@DisplayName("Login Sucessful Scenario")
public class LoginITCase extends AbstractITCase {
    private final static Logger LOGGER = LoggerFactory.getLogger(LoginITCase.class);

    @Autowired
    LoginPage loginPage;

    @Test
    @DisplayName("Entering user and password")
    @Order(1)
    public void enterUsernameAndPassword() {
        LOGGER.info("-- enterUsernameAndPassword method started");
        driver.get(SetupProps.getDokaUrl());
        Assertions.assertTimeout(Duration.ofMinutes(1), () -> {
            loginPage.enterUsernameAndPassword();
        });
        LOGGER.info("-- enterUsernameAndPassword method finished");
    }

    @Test
    @DisplayName("Click button to login")
    @Order(2)
    public void clickButtonOkToLoggin() {
        LOGGER.info("-- clickButtonOkToLoggin method started");
        Assertions.assertTimeout(Duration.ofMinutes(1), () -> {
            loginPage.clickButtonToLogin();
            loginPage.isLoginSucessful();
        });
        LOGGER.info("-- clickButtonOkToLoggin method finished");
    }
}

封装测试行为的接口(由 AbstractITCase 类实现并继承给它的所有子类:

@Component(value = "loginTest")
@Tag("IntegrationTest")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
public @interface IntegrationTest {

}

标签: javaspringmaven-3junit5

解决方案


问题是我注册的扩展在内部引发了一个错误,与 JUnit 5 和 Maven 上的配置无关。

创建此扩展是为了在测试的生命周期中处理 ExtentReports API,创建报告测试对象,逐步记录结果,最后将报告刷新到 HTML 文件。


推荐阅读