如何为黄瓜+ Testng框架生成范围报告

时间:2019-05-23 11:39:06

标签: cucumber testng extentreports

如何以这种方式生成Cucumber + Testng框架的范围报告,使得在每种情况下我都可以捕获屏幕快照,而无需在步骤定义文件中为每种情况重复执行代码

我已经使用Cucumber + Testng设置了测试框架。但是,我需要范围报告,但不确定如何通过testNG运行器类实现它,而无需在步骤定义的每种情况下实际重复执行代码。因此,想法是在一个地方编写代码,就像使用将在每种情况下运行的黄瓜挂钩一样。

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 个答案:

答案 0 :(得分:0)

您的lofInfo为null,应该是这样

    @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);
}
    }