我有一个有多个方法的TestNG测试。范围报告在主类中有效,但当我尝试为其他方法编写日志时,我得到了空指针异常。所有教程都指向在主方法中编写日志,但没有指向其他方法。我已经努力寻找解决方案一个星期了。有人能帮我吗?谢谢
我的代码是这样的
@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();
}
}
首先,我建议使用版本3而不是版本2,
正如我在您的代码中看到的,您已经定义了测试定义,但对于要在其中生成的方法,没有这样的日志,
要生成日志,请参考以下内容:
您可以在任何方法中使用相同的方式,
extentTest.log(LogStatus.INFO, "Test Case Details");
在这里,ExtentTest的对象需要声明为类变量,以便您可以在类中的任何位置访问它。
如果您想为登录创建不同的测试部分。LoginToClient() 方法,您可以这样定义它:
Public void LoginToClient()
{
extentTest = extent.startTest("Login Test");
driver.findElement(By.id("username")).SendKeys(username);
extentTest.log(LogStatus.INFO, "User Name: " +username);
}
希望它能像你想生成的那样工作。
请检查这些链接以获取答案:
如果您有一个报告类say,它侦听TestNG Listner并在其中实现了ExtentReport代码,那么您可以使用Reporter对象获得TestCase步骤,请参见下面的内容。
请注意,报告者。TestNG的日志没有任何日志类型的定义,如信息、致命等。。它只是添加日志消息。
测试用例:
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));
}
}
}
我们在我的项目中使用范围报告。我想访问运行时存储的值。例如,在测试用例的catch块中,我有一行。 在最后一个块中,我试图创建一个函数,如果测试用例失败,我将需要使用日志函数的值并将其存储用于某种目的。 有可能吗?我正在POM框架中使用java和selenium。
我正在从事一个基于Selenium/testng/java/gradle的项目,该项目采用了针对webdriver和extenttest对象的ThreadLocal方法。每当我的测试用例失败时,我都会使用RetryListener再次运行失败的测试用例1次。若它是第二次通过,我的结果仍然在扩展报告中显示为“失败”(注意,所有迭代都记录在html报告中的单个测试节点中)。stackoverflow对
我试图用ExtentReport和TestNG执行我的基本项目测试,但当我执行2个类时,ExtentTestManager中的“categoryName”。java由第二个测试填充,而第一个测试没有运行。我尝试实现一个LocalThread来完成这项任务,但我无法实现。。。 扩展测试管理器.java 范围曼安格.java 测试侦听器.java SearchInGoogleTest.java Tes
当我尝试使用Cucumber最新版本4.7.1(即“io.cucumber”)时,使用范围报告3.0不会生成报告。我尝试了不同版本的范围报告,但仍然正确生成输出。 我尝试了Cucumber和Extent Report之间的不同组合版本,但仍然没有输出。有人可以在这里发光来提高输出。 代码: 慰问: oader.java:362NoClassDefFoundError: gherkin/format
5.4.2 多工程报告 在一个既有应用工程又有库工程的多工程里,当在同时运行所有测试的时候,生成一个包含所有测试结果的报告是非常有用的。 为了达到这一目的,需要同一构件中的另外一个插件,可以通过如下方式应用: buildscript { repositories { mavenCentral() } dependencies { classp
将崩溃日志提交给远程服务器 进程: Main, Renderer 以下是一个自动提交崩溃日志到服务器的示例 const { crashReporter } = require('electron') crashReporter.start({ productName: 'YourName', companyName: 'YourCompany', submitURL: 'https:/