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

如何为cucumber测试框架生成程度报告

谭骏
2023-03-14

如何为cucumber testng framework生成扩展报告,以便在每个场景失败时都能捕获屏幕截图,而无需在步骤定义文件中的每个场景中重复代码

我已经使用Cucumber Testng设置了测试框架。然而,我需要数据块报告,但不确定如何通过testNG runner类实现它,而不必在步骤定义的每个场景中实际重复代码。因此,我们的想法是在一个地方编写代码,就像使用cucumber钩子一样,它将在每个场景中运行。

I Have already tried the approach with TestNG listener with Extent report but with this the drawback is I have to write the code every time for each and every scenario. LIke below I have ITestListnerImpl.java, ExtentReportListner and YouTubeChannelValidationStepDef where for each scenario I have to repeat the loginfo and screencapture methods

代码: ItestListerner.java

package com.testuatomation.Listeners;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;

import com.aventstack.extentreports.ExtentReports;

public class ITestListenerImpl extends ExtentReportListener implements ITestListener {

    private static ExtentReports extent;

    @Override
    public void onFinish(ITestContext arg0) {
        // TODO Auto-generated method stub
        extent.flush();
        System.out.println("Execution completed on UAT env ......");                
    }

    @Override
    public void onStart(ITestContext arg0) {
        // TODO Auto-generated method stub
        extent = setUp();           
        System.out.println("Execution started on UAT env ......");          
    }

    @Override
    public void onTestFailedButWithinSuccessPercentage(ITestResult arg0){
        // TODO Auto-generated method stub          
    }

    @Override
    public void onTestFailure(ITestResult arg0) {
        // TODO Auto-generated method stub
        System.out.println("FAILURE");          
    }

    @Override
    public void onTestSkipped(ITestResult arg0) {
        System.out.println("SKIP");

    }

    @Override
    public void onTestStart(ITestResult arg0) {
        System.out.println("STARTED");

    }

    @Override
    public void onTestSuccess(ITestResult arg0) {
        // TODO Auto-generated method stub
        System.out.println("PASS-----");    
    }       

}

ExtentReportListener。JAVA

package com.testuatomation.Listeners;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;

public class ExtentReportListener {

    public static ExtentHtmlReporter report = null;
    public static ExtentReports extent = null;
    public static ExtentTest test = null;

    public static ExtentReports setUp() {
        String reportLocation = "./Reports/Extent_Report.html";
        report = new ExtentHtmlReporter(reportLocation);        
        report.config().setDocumentTitle("Automation Test Report");
        report.config().setReportName("Automation Test Report");
        report.config().setTheme(Theme.STANDARD);       
        System.out.println("Extent Report location initialized . . .");
        report.start();

        extent = new ExtentReports();
        extent.attachReporter(report);      
        extent.setSystemInfo("Application", "Youtube");
        extent.setSystemInfo("Operating System", System.getProperty("os.name"));
        extent.setSystemInfo("User Name", System.getProperty("user.name"));
        System.out.println("System Info. set in Extent Report");        
        return extent;
    }

    public static void testStepHandle(String teststatus,WebDriver driver,ExtentTest extenttest,Throwable throwable) {
        switch (teststatus) {
        case "FAIL":        
            extenttest.fail(MarkupHelper.createLabel("Test Case is Failed : ", ExtentColor.RED));           
            extenttest.error(throwable.fillInStackTrace());

            try {
                extenttest.addScreenCaptureFromPath(captureScreenShot(driver));
                } catch (IOException e) {
                e.printStackTrace();
                }

            if (driver != null) {
                driver.quit();
            }       
        break;

        case "PASS":            
            extenttest.pass(MarkupHelper.createLabel("Test Case is Passed : ", ExtentColor.GREEN));
            break;

        default:
            break;
        }
    }

    public static String captureScreenShot(WebDriver driver) throws IOException {
        TakesScreenshot screen = (TakesScreenshot) driver;
        File src = screen.getScreenshotAs(OutputType.FILE);
        String dest = "C:\\Users\\Prateek.Nehra\\workspace\\SeleniumCucumberBDDFramework\\screenshots\\" + getcurrentdateandtime() + ".png";
        File target = new File(dest);
        FileUtils.copyFile(src, target);
        return dest;
    }

    private static String getcurrentdateandtime() {
        String str = null;
        try {
            DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss:SSS");
            Date date = new Date();
            str = dateFormat.format(date);
            str = str.replace(" ", "").replaceAll("/", "").replaceAll(":", "");
        } catch (Exception e) {
        }
        return str;
    }       
}

YoutubeChannelValidationsStepDef.java

package com.testautomation.StepDef;

import java.util.Properties;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.GherkinKeyword;
import com.aventstack.extentreports.gherkin.model.Feature;
import com.aventstack.extentreports.gherkin.model.Scenario;
import com.testuatomation.Listeners.ExtentReportListener;
import com.testautomation.PageObjects.YoutubeChannelPage;
import com.testautomation.PageObjects.YoutubeResultPage;
import com.testautomation.PageObjects.YoutubeSearchPage;
import com.testautomation.Utility.BrowserUtility;
import com.testautomation.Utility.PropertiesFileReader;

import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class YoutubeChannelValidationsStepDef extends ExtentReportListener
{
    PropertiesFileReader obj= new PropertiesFileReader();
    private WebDriver driver;

    @Given("^Open Chrome browser with URL$")
    public void open_Chrome_browser_with_URL() throws Throwable
    {
        ExtentTest logInfo=null;
        try {
            test = extent.createTest(Feature.class, "Youtube channel name validation");                         
            test=test.createNode(Scenario.class, "Youtube channel name validations");                       
            logInfo=test.createNode(new GherkinKeyword("Given"), "open_Chrome_browser_with_URL");
            Properties properties=obj.getProperty();        
            driver=BrowserUtility.OpenBrowser(driver, properties.getProperty("browser.name"), properties.getProperty("browser.baseURL"));

            logInfo.pass("Opened chrome browser and entered url");
            logInfo.addScreenCaptureFromPath(captureScreenShot(driver));            

        } catch (AssertionError | Exception e) {
            testStepHandle("FAIL",driver,logInfo,e);            
        }       
    }

    @When("^Search selenium tutorial$")
    public void search_selenium_tutorial() throws Throwable 
    {
        ExtentTest logInfo=null;
        try {

            logInfo=test.createNode(new GherkinKeyword("When"), "search_selenium_tutorial");
            new YoutubeSearchPage(driver).NavigateToResultPage("selenium by bakkappa n");
            logInfo.pass("Searching selenium tutorial");
            logInfo.addScreenCaptureFromPath(captureScreenShot(driver));

        } catch (AssertionError | Exception e) {
            testStepHandle("FAIL",driver,logInfo,e);            
        }


    }

    @When("^Search selenium tutorial \"([^\"]*)\"$")
    public void search_selenium_tutorial(String searchString) throws Throwable 
    {
        new YoutubeSearchPage(driver).NavigateToResultPage(searchString);
    }

    @When("^Click on channel name$")
    public void click_on_channel_name() throws Throwable 
    {
        ExtentTest logInfo=null;
        try {

            logInfo=test.createNode(new GherkinKeyword("When"), "click_on_channel_name");
            new YoutubeResultPage(driver).NavigateToChannel();
            logInfo.pass("Clicked on the channel name");
            logInfo.addScreenCaptureFromPath(captureScreenShot(driver));

        } catch (AssertionError | Exception e) {
            testStepHandle("FAIL",driver,logInfo,e);            
        }


    }

    @Then("^Validate channel name$")
    public void validate_channel_name() throws Throwable
    {
        ExtentTest logInfo=null;
        try {                                   
            logInfo=test.createNode(new GherkinKeyword("Then"), "validate_channel_name");
            String expectedChannelName="1Selenium Java TestNG Tutorials - Bakkappa N - YouTube";
            String actualChannelName=new YoutubeChannelPage(driver).getTitle();
            Assert.assertEquals(actualChannelName, expectedChannelName,"Channel names are not matching");  //
            logInfo.pass("Validated channel title");
            logInfo.addScreenCaptureFromPath(captureScreenShot(driver));
            System.out.println("closing browser");
            driver.quit();

        } catch (AssertionError | Exception e) {
            testStepHandle("FAIL",driver,logInfo,e);            
        }

    }

}

共有1个答案

乐正心水
2023-03-14

你的lofInfo是空的,应该是这样的

    @Then("Open Chrome browser with URL")
    public void open_Chrome_browser_with_URL() {
        try {
            logInfo = test.createNode(new GherkinKeyword("Then"), "open_Chrome_browser_with_URL");

//YOUR CODE HERE

            logInfo.pass("Chrome opens URL");
        }
        catch (AssertionError | Exception e) {testStepHandle("FAIL", d, logInfo, e);
}
    }
 类似资料:
  • 测试启动后,结果是测试通过,但测试框架意外退出。如何解决? 试样 测试特性 输出 配置 http://maven.apache.org/xsd/maven-4.0.0.xsd"

  • 通过命令行报告生成工具生成报告时,我得到以下错误。 线程“main”ru.yandex.qatools.allure.data中出现异常。ReportGenerationException on:在ru.yandex.qatools.allure.data.AllureReportGenerator中找不到任何诱惑结果。在ru.yandex.qatools.allure.data.AllureRe

  • 本文向大家介绍jmeter如何自动生成测试报告,包括了jmeter如何自动生成测试报告的使用技巧和注意事项,需要的朋友参考一下 1、准备.jmx脚本文件 2、在脚本文件路径下执行cmd命令: 参数解析:   ● -n: 非GUI模式执行JMeter   ● -t: 执行测试文件所在的位置   ● -l: 指定生成测试结果的保存文件,.jtl文件格式   ● -e: 测试结束后,生成测试报告   ●

  • 我正试图利用Jenkins中的“发布JUnit测试结果报告”,但无法让它为我的android测试项目工作。我在Jenkins的android测试项目的设置基于以下指南:https://wiki.jenkins-ci.org/display/Jenkins/building+an+android+app+和+test+project 我希望有人能发布一个简单的逐步指南,说明如何从测试运行中获得JUn

  • 我有一个基于模块的selenium java框架。它是现有的和古老的。我不知道如何将Exent报告集成到它中。它有诱惑力报告,输出是xml格式的。人们想要可共享的html报告。请帮忙。

  • 我们的团队使用JUnit作为一个大型老项目的基础测试框架。我们最近迁移到Maven,并决定尝试一个名为Allure的JUnit新报告。我们从下面的示例中将依赖项和插件复制到pom.XML,但在target/folder中没有生成XML数据。Maven输出中不会发出警告或错误。有人知道怎么会这样吗?