0

我有一个有多种方法的 TestNG 测试。范围报告在主类中有效,但是当我尝试为其他方法编写日志时,我得到空指针异常。所有教程都指向在 main 方法中写入日志,而不是其他方法。一个星期以来,我一直在努力寻找解决方案。有人可以帮我吗?谢谢

我的代码是这样的

@Test
public void TestOne()
{
extentTest = extent.startTest("TestOne");
Login.LoginToClient();
Access.AccessMainPage();
-
-
}


Public void LoginToClient()

{
  ***How can write an extent report log here for example - "Enter Username"
  driver.findElement(By.id("username")).SendKeys(username)
  -
  -
}

以下是在主测试中写的

@BeforeTest
	public void setExtent(){
		extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
		extent.addSystemInfo("Host Name", "Calcutta");
		extent.addSystemInfo("User Name", "Admin");
		extent.addSystemInfo("Environment", "QA");		
	}
	
	@AfterMethod
	public void tearDown(ITestResult result) throws IOException {
		
		if(result.getStatus()==ITestResult.FAILURE){
			
			//to add name in extent report
			extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getName()); 
			 //to add error/exception in extent report
			extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getThrowable());
			String screenshotPath = Screenshots.getScreenshot(driver, result.getName());
			//to add screenshot in extent report
			extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath)); 
			
		}
		else if(result.getStatus()==ITestResult.SKIP){
			extentTest.log(LogStatus.SKIP, "Test Case SKIPPED IS " + result.getName());
		}
		else if(result.getStatus()==ITestResult.SUCCESS){
			extentTest.log(LogStatus.PASS, "Test Case PASSED IS " + result.getName());
		}
		extent.endTest(extentTest); 
	}
	

我的完整代码在这里

package yellowfin.bi.test;

import java.awt.AWTException;
import java.io.IOException;
import java.lang.reflect.Method;

import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import y.bi.create.reports.charts.ContentMenuButton;
import y.bi.create.reports.charts.ReportChartBuilder;
import y.bi.create.reports.charts.ReportFormattingPage;
import y.bi.create.reports.charts.ViewForReport;
import y.bi.login.loginPage;
import y.bi.logout.Logout;
import y.bi.screenshots.Screenshots;
import y.bi.utils.Printscreen;
import y.bi.utils.BrowserFactory;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

public class ReportFormatting {
	private EventFiringWebDriver driver;
	private loginPage login;
	private Logout logout;
	private ContentMenuButton createContentMenuButton;
	private ViewForReport reportView;
	private ReportChartBuilder createChart;
	Printscreen ps;
	private ReportFormattingPage reportFormattingPage;
	public ExtentReports extent;
	public ExtentTest logger;

	
	@BeforeSuite(enabled = true)
	public void setUpTheTest() {
		driver = (EventFiringWebDriver) BrowserFactory.selectBrowser("chrome");
	}
	
	@Parameters({ "yellowfinURL" })
	@BeforeTest(enabled = true)
	public void instantiatePages(String url) {
		driver.get(url);
		login = new loginPage(driver);
		logout = new Logout(driver);
		createContentMenuButton = new ContentMenuButton(driver);
		reportView = new ViewForReport(driver);
		createChart = new ReportChartBuilder(driver);
		ps = new Printscreen(driver);
		reportFormattingPage = new ReportFormattingPage(driver);
		
	}
	
	@BeforeTest
	public void setExtent(){
		extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
		extent.addSystemInfo("Host Name", "Calcutta");
		extent.addSystemInfo("User Name", "Admin");
		extent.addSystemInfo("Environment", "QA");		
	}

	
	
	@AfterMethod(alwaysRun=true)
	  public void TearDown_AM(ITestResult result) throws IOException
	  {
	      System.out.println("@After Method");
	    try
	    { 
	        if(result.getStatus()==ITestResult.FAILURE)
	        {
	        	String screenshotPath = Screenshots.getScreenshot(driver, result.getName());
	            String image= logger.addScreenCapture(screenshotPath);
	            System.out.println(image);
	            String TestCaseName = this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed";
	            logger.log(LogStatus.FAIL, TestCaseName  + logger.addScreenCapture(screenshotPath));
	            
	        }
	        else if(result.getStatus()==ITestResult.SUCCESS)
	        {
	            logger.log(LogStatus.PASS, this.getClass().getSimpleName() + " Test Case Success"); 
	        }
	        else if(result.getStatus()==ITestResult.SKIP)
	        {
	            logger.log(LogStatus.SKIP, this.getClass().getSimpleName() + " Test Case Skipped");
	        }
	        extent.endTest(logger);
	        extent.flush();

	    }
	    catch(Throwable t)
	    {
	        logger.log(LogStatus.ERROR,t.fillInStackTrace());
	    }

	  }
	
	
	@Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "fontType" ,"fontSize"})
	@Test(testName = "validateDataSection", enabled = true, groups = {"Report Formatting : Data"}, alwaysRun = true, priority=1)
	public void ValidateDataSection(String username, String password, String viewName, String r1, String r2, String r3,	String r4, String r5, String ftype, String fsize)  {
	
		logger = extent.startTest("ValidateDataSection");
		
        	
		login.loginToTenant(username, password);
		// select view from content menu button
		createContentMenuButton.setContentMenuButton();
		// choose view
		reportView.selectView(viewName);
		// create the report in report builder
		createChart.createReport(r1, r2, r3, r4, r5);
		
		//Checks the style "Font Type, Font Size, Bold Italic"
		reportFormattingPage.DataSection(ftype,fsize);
		
		// Access Row Highlight
		reportFormattingPage.RowHighlight();
		
	    logout.performLogout();
		

	}
	
	
	@Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "headerFontType", "headerFontSize", "borderWidth"})
	@Test(testName = "Validate Column & Row Headings and Border", enabled = false, groups = {"Report Formatting : Column & Row Headings and Border"}, alwaysRun = true, priority=1)
	public void ValidateColumnandRowHeadingsandBorder(String username, String password, String viewName, String r1, String r2, String r3,	String r4, String r5, String headerFontType, String headerFontSize, String borderWidth) {
		logger = extent.startTest("ValidateColumnandRowHeadingsandBorder");
		
			
		login.loginToTenant(username, password);
		// select view from content menu button
		createContentMenuButton.setContentMenuButton();
		// choose view
		reportView.selectView(viewName);
		// create the report in report builder
		createChart.createReport(r1, r2, r3, r4, r5);
		
		// validates the column and Row headings
		reportFormattingPage.ColumnAndRowHandling(headerFontType, headerFontSize);
		
		// Validates the border
		reportFormattingPage.Border(borderWidth);
		
		logout.performLogout();

	}
	
	@Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "displayTitleFontType", "displayTitleFontSize", "displayDescFontType", "displayDescFontSize"})
	@Test(testName = "Validate Title and Description", enabled = false, groups = {"Report Formatting : Title and Description"}, alwaysRun = true, priority=1)
	public void ValidateTitleandDescription(String username, String password, String viewName, String r1, String r2, String r3,	String r4, String r5, String displayTitleFontType, String displayTitleFontSize, String displayDescFontType, String displayDescFontSize)  {
		logger = extent.startTest("ValidateTitleandDescription");
				
		login.loginToTenant(username, password);
		// select view from content menu button
		createContentMenuButton.setContentMenuButton();
		// choose view
		reportView.selectView(viewName);
		// create the report in report builder
		createChart.createReport(r1, r2, r3, r4, r5);
		
		//Validates Title and Description
		reportFormattingPage.TitleAndDescription(displayTitleFontType,displayTitleFontSize,displayDescFontType,displayDescFontSize);
		
		logout.performLogout();

	}
	
	

	@Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "displayTitleFontType", "displayTitleFontSize", "displayDescFontType", "displayDescFontSize"})
	@Test(testName = "Validate header / Footer and Table sort", enabled = false, groups = {"Report Formatting : header / Footer and Table sort"}, alwaysRun = true, priority=1)
	public void ValidateHeaderFooterandTableSort(String username, String password, String viewName, String r1, String r2, String r3,	String r4, String r5, String displayTitleFontType, String displayTitleFontSize, String displayDescFontType, String displayDescFontSize)  {
		
		logger = extent.startTest("ValidateHeaderFooterandTableSort");
			
		login.loginToTenant(username, password);
		// select view from content menu button
		createContentMenuButton.setContentMenuButton();
		// choose view
		reportView.selectView(viewName);
		// create the report in report builder
		createChart.createReport(r1, r2, r3, r4, r5);
		
		//Validates Header and Footer page
		reportFormattingPage.HeaderAndFooter();
		
		//Validates Table sort
		reportFormattingPage.TableSort();
		logout.performLogout();
		

	}
	
	@AfterTest
	public void endReport(){
		extent.flush();
		extent.close();
		driver.quit();
	}
	
}

import java.awt.Robot;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.BeforeTest;
import org.testng.asserts.SoftAssert;

import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

import yellowfin.bi.screenshots.Screenshots;


public class ReportFormattingPage {
	static WebDriver driver;
	static long d = 2000;
	String xpathElements="//div[@class='toggleSwitchSliderInner']";		
	String workingDir = System.getProperty("user.dir");
	ReportFormat rf = new ReportFormat();
	SoftAssert sa= new SoftAssert();
	Screenshots screenshot = new Screenshots();
	public ExtentReports extent;
	public ExtentTest logger;
	
	@BeforeTest
	public void setExtent(){
		extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
		extent.addSystemInfo("Host Name", "Calcutta");
		extent.addSystemInfo("User Name", "Admin");
		extent.addSystemInfo("Environment", "QA");		
	}
	
	@SuppressWarnings("static-access")
	public ReportFormattingPage(WebDriver driver) {
	
		this.driver = driver;
	}	
	
	public void DataSection(String FontType, String FontSize) 

	{
		
		try {
			    logger = extent.startTest("ValidateDataSection");			
				//Click on Report Format
			    logger.log(LogStatus.INFO, "Access Report Format Button");
				rf.accessReportFormat(driver);
				//Click on the Toggle switch
				
				driver.findElement(By.cssSelector("div.toggleSwitchSliderInner")).click();
				Thread.sleep(d);
				//Select the font type
				new Select(driver.findElement(By.cssSelector("div.fontDropDown > div.styledSelect.customSelect > select"))).selectByVisibleText(FontType);
				Thread.sleep(d);
				//Select the font size
				driver.findElement(By.cssSelector("input.broadcastInput")).clear();
				driver.findElement(By.cssSelector("input.broadcastInput")).sendKeys(FontSize);
				//Click on Bold
				driver.findElement(By.cssSelector("div.fontStyleOptions > div > img")).click();
				Thread.sleep(d);
				//Select italic and underline
				driver.findElement(By.xpath("//img[@src='images/format_italic.png']")).click();
				driver.findElement(By.xpath("//img[@src='images/format_underline.png']")).click();
				   
				//Changing the color of the text
				driver.findElement(By.xpath("//div[@class='sp-preview-inner']")).click();	     
				rf.dragAndDrop(driver);
				driver.findElement(By.xpath("(//span[@id='chooseColourText'])")).click();
				//Row shading Default
				driver.findElement(By.xpath("//td[contains(text(), 'Default')]")).click();
				// Row Shading Alternative ------------------------------------------------------------
				driver.findElement(By.xpath("//td[contains(text(), 'Alternating')]")).click();
				//click on the Alternate Row Color  
				driver.findElement(By.xpath("(//div[contains(text(), 'Define a color to be applied to every second row in the table.')]//following::div[@class='backboneColourPicker'])[1]")).click();
				//Select the color  
				driver.findElement(By.xpath("(//span[@style='background-color:rgb(143, 80, 157);'])[3]")).click();
				// Click on close and access the design page
				rf.clickCloseAndAccessDesignPage(driver);
				Thread.sleep(d);
				screenshot.captureScreenShot(driver, "RowShadingAlternative");
				//Click on Report Format
				rf.accessReportFormat(driver);
				//RowShading none ------------------------------------------------------------------------------------
				driver.findElement(By.xpath("//td[contains(text(), 'None')]")).click();
				// Click on close and access the design page
			    rf.clickCloseAndAccessDesignPage(driver);
			    screenshot.captureScreenShot(driver, "RowShadingNone");
				//Click on Report Format
				rf.accessReportFormat(driver);
				rf.clickCloseAndAccessDesignPage(driver);
				//Assertions
				rf.DataSectionAssertions(driver);
				Thread.sleep(d);	
				screenshot.captureScreenShot(driver, "RowShadingDefault");
	
	}
	
	catch (Exception e) {
		  e.printStackTrace();
	}
	
	}
	
	   
	public void RowHighlight() 
	   
	   {  
		
		try {
			   //Click on Report Format
			   rf.accessReportFormat(driver);
			   // Click on the toggle switch for the Row Highlight field
			   driver.findElement(By.cssSelector("div.controlContainer > div.toggleSwitchSlider > div.toggleSwitchSliderInner")).click();
			   // Click on Row Highlight color
			   driver.findElement(By.cssSelector("div.sp-preview-inner.no-colour")).click();
			   // Select the color
			   driver.findElement(By.xpath("(//span[@style='background-color:rgb(124, 187, 0);'])[3]")).click();
			   // Click on close and access the design page
			   rf.clickCloseAndAccessDesignPage(driver);
			   Robot robot = new Robot();
			   robot.mouseMove(200,600);
			   robot.delay(1500);
			   robot.mouseMove(200,900);
			   Thread.sleep(d);
			   screenshot.captureScreenShot(driver, "RowHighlight");
	
   	}
		
	catch (Exception e) {
			  e.printStackTrace();
	        	}
		    }
	   

4

2 回答 2

1

请检查这些链接以获得答案:

如果您有一个报告类说哪个侦听 TestNG 列表器并在其中实现了 ExtentReport 代码,您可以使用 Reporter 对象获取 TestCase 步骤,请参见下文。

请注意,TestNG 的 Reporter .log 没有任何日志类型的定义,如 INFO、FATAL 等。它只是添加了日志消息。

测试用例:

public class TC_1 extends BaseClass{
    @Test (priority=0)
    public void addNotes()  throws Exception  
    {   
        if (super.search("VALUE"))
        {
            logger.info("Search is Successful");
            Reporter.log("Search is Successful");
            Assert.assertTrue(true);
        }
     }

报告:

public class Reporting extends TestListenerAdapter
{
public ExtentHtmlReporter htmlReporter;
    public ExtentReports extent;
    public ExtentTest logger;
public void onStart(ITestContext testContext)
    {
        String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());//time stamp
        String repName="Test-Report-"+timeStamp+".html";

        htmlReporter=new ExtentHtmlReporter(System.getProperty("user.dir")+ "/test-output/"+repName);//specify location of the report
        htmlReporter.loadXMLConfig(System.getProperty("user.dir")+ "/extent-config.xml");

        extent=new ExtentReports();

        extent.attachReporter(htmlReporter);

        htmlReporter.config().setDocumentTitle("Test Project"); 
        htmlReporter.config().setReportName("Functional Test Automation Report"); 
        htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP); 
        htmlReporter.config().setTheme(Theme.DARK);
    }

public void onTestSuccess(ITestResult tr)
    {
        logger=extent.createTest(tr.getName()); 
        logger.log(Status.PASS,MarkupHelper.createLabel(tr.getName(),ExtentColor.GREEN)); 

List<String> reporterMessages = Reporter.getOutput(tr);
                for (int i = 0; i < reporterMessages.size(); i++) 
            {
                    System.out.println(reporterMessages.get(i));
                    logger.info(reporterMessages.get(i)); 
        }

    }
}
于 2019-03-18T19:01:40.847 回答
0

首先,我建议使用版本 3而不是版本 2,

正如我在您的代码中看到的那样,您已经定义了测试定义,但是您想要生成的方法没有此类日志,

请参考以下,生成日志:

您可以在任何方法中使用相同的方式,

extentTest.log(LogStatus.INFO, "Test Case Details");

这里的 ExtentTest 对象需要声明为 Class 变量,所以你可以在类中的任何地方访问它。

如果你想为Login.LoginToClient();方法创建不同的测试部分,你可以像这样定义它:

Public void LoginToClient()
{  
  extentTest = extent.startTest("Login Test");

  driver.findElement(By.id("username")).SendKeys(username);

  extentTest.log(LogStatus.INFO, "User Name: " +username);  
}

希望它会像你想要的那样工作。

于 2018-05-15T04:59:20.607 回答