在Junit 5中,如何从扩展中调用测试类方法?

如何解决在Junit 5中,如何从扩展中调用测试类方法?

在Junit 5中,我试图从扩展名运行测试类方法。我正在使用Junit 5扩展接口TestWatcher,并覆盖了testFailed()方法。

此扩展的目的是对测试类的Selenium WebDriver浏览器中的故障进行截屏,并将其附加到该测试的Allure报告中。测试类方法具有实例化的浏览器和用于附加到Allure的注释。而且我的takeScreenshot方法依赖于浏览器和测试类中的testName字符串才能正确运行。

package utils;

public class ScreenshotOnFailureExtension implements TestWatcher{
    @Override
    public void testFailed(ExtensionContext context,Throwable cause) {
        try {
            Object clazz = context.getRequiredTestInstance();
            Method takeScreenshot = clazz.getClass().getMethod("takeScreenshot");
            takeScreenshot.setAccessible(true);
            Object test = clazz.getClass().getConstructor().newInstance();
            takeScreenshot.invoke(test);
        } catch (Exception e) {
            e.printStackTrace();
        } 
}

我的测试类中的代码是这样的:

package tests;

@ExtendWith(ScreenshotOnFailureExtension.class)
public class MyTest implements Config {
    public WebDriver driver;
    public String testName;

//bunch of Junit5 annotations with functions to initialize above variables omitted...

    //take a screen shot
    public void takeScreenshot() {
        System.out.println("Taking screenshot.");
        byte[] srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
        saveScreenshot(srcFile,testName+ ".png");
    }
    
    //this attaches screenshot to an allure test result
    @Attachment(value = "{testName}",type = "image/png")
    public byte[] saveScreenshot(byte[] screenShot,String testName) {
        System.out.println("Attaching screenshot to Allure report");
        return screenShot;
    }
}

在测试方法中从@AfterEach调用时,上述测试类能够正确拍摄屏幕截图。但是我只想失败就解决这个问题。

运行测试时,它将调用takeScreenshot,但是在执行测试时会给出异常:

获取screenshot.java.lang.reflect.InvocationTargetException

在 java.base / jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(本机 方法) java.base / jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 在 java.base / jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在java.base / java.lang.reflect.Method.invoke(Method.java:566) utils.ScreenshotOnFailureExtension.testFailed(ScreenshotOnFailureExtension.java:49) 在 org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda $ nodeFinished $ 14(TestMethodTestDescriptor.java:299) 在 org.junit.jupiter.engine.descriptor.MethodBasedTestDescriptor.lambda $ invokeTestWatchers $ 3(MethodBasedTestDescriptor.java:134) 在java.base / java.util.ArrayList.forEach(ArrayList.java:1540)在 org.junit.jupiter.engine.descriptor.MethodBasedTestDescriptor.invokeTestWatchers(MethodBasedTestDescriptor.java:132) 在 org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.nodeFinished(TestMethodTestDescriptor.java:290) 在 org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.nodeFinished(TestMethodTestDescriptor.java:65) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.reportCompletion(NodeTestTask.java:176) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:89) 在java.base / java.util.ArrayList.forEach(ArrayList.java:1540)在 org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda $ executeRecursively $ 5(NodeTestTask.java:143) 在 org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda $ executeRecursively $ 7(NodeTestTask.java:129) 在 org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda $ executeRecursively $ 8(NodeTestTask.java:127) 在 org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84) 在java.base / java.util.ArrayList.forEach(ArrayList.java:1540)在 org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda $ executeRecursively $ 5(NodeTestTask.java:143) 在 org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda $ executeRecursively $ 7(NodeTestTask.java:129) 在 org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda $ executeRecursively $ 8(NodeTestTask.java:127) 在 org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126) 在 org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84) 在 org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32) 在 org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57) 在 org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51) 在 org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108) 在 org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88) 在 org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda $ execute $ 0(EngineExecutionOrchestrator.java:54) 在 org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67) 在 org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52) 在 org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96) 在 org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75) 在 org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89) 在 org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41) 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541) 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763) 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463) 在 org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209) 由以下原因引起:java.lang.NullPointerException tests.Base.takeScreenshot(Base.java:240)...还有49个

您可以看到在该方法的下一行代码引起的NullPointerException之前输出了我的日志记录语句(引用测试实例中的driver)。是否有一种在上下文中触发现有测试实例的takeScreenshot()方法的正确方法?

OR

如果有一种更简单的方法可以直接通过测试的@AfterEach方法对失败进行屏幕截图,请告诉我。似乎是一个非常基本的用例。 :)

解决方法

IMO,问题出在您描述的流程中。 JUnit为每个测试方法创建一个Test类的新实例(尽管可以更改)。

更好的方法是:

  1. 使扩展名“有状态”,以使其包含对Web驱动程序的引用。
  2. 请勿在测试中实现takeScreenshot方法,而应在扩展名(私有方法)中执行
  3. 在扩展中,实现回调并将WebDriver实例(通过反射)“注入”到测试中(如果需要在测试中使用它的话)。这将确保测试以正确实例化的“状态”(webdriver的实例)运行。
  4. 在扩展程序中实现逻辑“如果测试方法失败,则调用扩展程序takeScreenshot的私有方法
,

您不应该执行从扩展内部实例化测试类之类的事情,框架应该处理所有事情。

请参考文档中的https://junit.org/junit5/docs/current/user-guide/#extensions 5.9.1,然后查看this Q&A

您可以使用它,也可以按照评论中的建议修改TestWatcher以进行屏幕截图。您必须将驱动程序引用保存在ExtensionContext中才能访问它。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-