Как создать отчет по экстенту для фреймворка cucumber + testng - PullRequest
0 голосов
/ 23 мая 2019

Как создать отчет по экстентам для структуры 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);            
        }

    }

}
...