我有一个有多种方法的 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();
}
}