当前位置: 首页 > 知识库问答 >
问题:

不执行测试——JUnit 5程序mvn exec

方宜
2023-03-14

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

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

这是我执行.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-平台-启动器库以编程方式执行测试:

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 {

}

共有1个答案

别旻
2023-03-14

这个问题是由我注册的扩展引起的内部错误,与JUnit 5和Maven上的配置无关。

创建此扩展是为了在测试的生命周期中处理扩展报告应用编程接口,创建报告测试对象,逐步记录结果,最后将报告刷新为超文本标记语言文件。

 类似资料:
  • 右键点击Run可以很好地工作。我用 Intellijidea 2017.1.5, Gradle, JunitPlatformVersion='1.0.0-M6', JunitJupiterVersion='5.0.0-M6'

  • 我得堆栈: 想法2019.1.3 Springboot 2.1.6 Java 11 Maven 3.8.0 Groovy 2.5 史巴克1.3 JUnit jupiter 5.5.1 JUnit vintage 5.5.1 GMavenPlus插件2.7.1 我们想开始在Spock测试框架中编写测试。我跟着这个howto,但没有成功。当我尝试运行所有测试时,我的spock测试没有运行。 我能运行一

  • 我有简单的测试 为什么maven和intellij不能执行Junit5测试?这方面的工作是什么?surefire版本应该已经支持JUnit5测试。

  • 我试图定义一个,如示例MockitoExtension所提供的,但无法成功地使用参数化的类实例。 期待着关于如何用在中实现接口的类的参数化实例测试接口的建议。

  • Maven执行 问题-这个自定义提供程序是否不再受支持,或者是否有任何解决方案可以使用、和/或执行测试? 注意-测试执行在JUnit-4中运行良好。

  • 我使用的是Eclipse Oxygen.3版本(4.7.3)。下面是我的JUnit测试类: 当我运行这个Junit测试时,eclipse不断弹出对话框,告诉我“没有tests found with test runner'JUnit5'”。为什么?