When i am trying to run my selenium tests the first test seem to work correctly but then i am recieving this error for the subsequent tests, Im after switching my tests over to an electron app so not sure if this is after causing a issue :
org.openqa.selenium.NoSuchSessionException: Session ID is null. Using WebDriver after calling quit()?
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
My set up page is:
public class SetUp extends TestRail {
private static ChromeDriver browser;
public static String urlHost;
public static String testEnv;
public static PageConfig pageConfig;
#Before
public void initialBrowser() {
if(browser == null) {
String projectLocation = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver", projectLocation + "/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("start-maximized");
options.addArguments("--disable-gpu");
options.addArguments("disable-infobars");
System.setProperty("webdriver.chrome.silentOutput", "true");
options.setBinary("C:/Users/ElectronApp.exe");
browser = new ChromeDriver(options);
//--------------------
pageConfig = new PageConfig(browser);
}
}
//method: To get the url configs for the environment used to run the test
//#parameter: dev or test. demo doesn't not have a separate front end url
public void beforeTest(#NotNull final String env) throws Exception {
testEnv = env;
System.out.println("TEST ENVIRONMENT: " + testEnv);
switch (env){
case "qa-84" :
urlHost = "http://ukdc1-docker-mx:84/qa/#/login";
break;
case "qa-85":
urlHost = "http://ukdc1-docker-mx:85/qa/#/login";
break;
default:
throw new Exception("Incorrect environment passed");
}
}
//method to close the browser after every cucumber scenario
#After
public void closeBrowser(Scenario scenario) throws IOException, APIException {
if(scenario.isFailed()){
try{
TakesScreenshot screenshot = (TakesScreenshot)browser;
File source = screenshot.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("logs/screenshots/" + scenario.getName() + ".png"));
System.out.println("Screenshot taken");
} catch (Exception e){
System.out.println("Exception while taking screenshot " + e.getMessage());
}
}
browser.quit();
writeResultToTestRail(scenario);
}
public void writeResultToTestRail(Scenario scenario) throws IOException, APIException {
String tesCaseID = new String();
for(String s: scenario.getSourceTagNames()){
if(s.contains("TestRail")){
int size = s.length();
int startOfID = s.indexOf('"');
tesCaseID = s.substring(startOfID + 1,size - 2);
}
Map data = new HashMap();
if(scenario.isFailed()){
data.put("status_id", 5);
data.put("comment", "Test Env: " + urlHost + "\n\n" + logError(scenario));
}else {
data.put("status_id", 1);
}
postTestCaseStatus("add_result_for_case/","3914", tesCaseID, data);
//3914
}
}
protected void getTestCaseDetailsInConsole(String testCaseId) throws IOException, APIException {
System.out.println(getTestCaseDetails(testCaseId));
}
private static String logError(Scenario scenario) {
try {
Class klass = ClassUtils.getClass("cucumber.runtime.java.JavaHookDefinition$ScenarioAdaptor" );
Field fieldScenario = FieldUtils.getField(klass, "scenario", true);
if (fieldScenario != null) {
fieldScenario.setAccessible(true);
Object objectScenario = fieldScenario.get(scenario);
Field fieldStepResults = objectScenario.getClass().getDeclaredField("stepResults" );
fieldStepResults.setAccessible(true);
ArrayList<Result> results = (ArrayList<Result>) fieldStepResults.get(objectScenario);
for (Result result : results) {
if (result.getError() != null) {
System.out.println(result.getError() + "\n\n" + result.getErrorMessage());
if(result.getErrorMessage().length() > 3100) {
return result.getErrorMessage().substring(0, 3100);
} else {
return result.getErrorMessage();
}
}
}
}
return "Fetching error logs from the scenario ran into some issue, please check jenkins logs";
} catch (IllegalAccessException | NoSuchFieldException | ClassNotFoundException e) {
return e.getMessage();
}
}
}
And My Page config:
public class PageConfig {
public ChromeDriver browser;
public PageConfig(ChromeDriver browser){
this.browser = browser;
}
//method: Get instance method can be called on any class, it helps to avoid to add a line every time a new PO is added to the project.
//#parameter: ClassName.class
//#example: PageConfig.GetInstance(LoginPage.class).onLoginPage(); where onLoginPage is an method of
LoginPage.
public <TPage extends BasePage> TPage GetInstance (Class<TPage> pageClass){
try {
return initElements(browser, pageClass);
}catch(Exception e){
e.printStackTrace();
throw e;
}
}
}
the error shows that your driver close before the execution of the code, so the code of #After is directly executed so what I think is that you forget to use #Test in your set up page because there is #Before and #After but I don't see #Test.
Related
I'm doing automation with Selenium - Page object Model & TestNG & Java. I have 2 testcases in 2 class files and i want to run all my tests in parallel
I passed driver and test object to all my pages.
When running my testng.xml with parallel="classes" two browser windows opened and only in one window, tests is running. The other window is closed. Eclipse showed me Null pointer exception.
Answer:
Later i understood that this is about usage of static in ExtentReport initialization. I corrected my code in reporter class.
Test Class-1:
public class CreateXCase extends SeleniumBase
{
#BeforeTest(alwaysRun=true )
public void setTestDetails()
{
author = System.getProperty("user.name");
testcaseName="Verify that X case is successfully created";
testcaseDec = "Create X Case";
category="Regression";
}
#Test(priority=2,groups = {"Regression"})
public void createCaseWithNewParticipants() throws Exception
{
new LoginPage(driver, test).login().quickNavigation_CASE()
.navigateToCreateCase().enterApplicantInformation()
.navigateToCaseSection().createCase();
}
}
Test Class-2:
public class CreateYcase extends SeleniumBase
{
#BeforeTest(alwaysRun=true )
public void setTestDetails()
{
author = System.getProperty("user.name");
testcaseName="Verify that Y case is successfully created";
testcaseDec = "Create Y Case";
category="Regression";
}
#Test(priority=1,groups = {"Regression"})
public void createCaseWithNewParticipants() throws Exception
{
new LoginPage(driver,test).login().quickNavigation_CASE()
.navigateToCreateCase().enterApplicantInformation()
.navigateToCaseSection().createCase();
}
SeleniumBase.java:
public class SeleniumBase extends Reporter implements Browser, Element
{
public static WebDriverWait wait;
#BeforeMethod(alwaysRun=true )
public void configureAndLaunch() throws IOException
{
driver = startApp(ReadPropertyFile.get("Browser"), ReadPropertyFile.get("URL"));
}
#Override
#AfterMethod (alwaysRun=true )
public void closeBrowser()
{
driver.quit();
}
#Override
public RemoteWebDriver startApp(String browser, String url)
{
try
{
if (browser.equalsIgnoreCase("chrome"))
{
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
driver = new ChromeDriver();
}
else if (browser.equalsIgnoreCase("firefox"))
{
System.setProperty("webdriver.gecko.driver", "./drivers/geckodriver.exe");
driver = new FirefoxDriver();
}
else if (browser.equalsIgnoreCase("ie"))
{
System.setProperty("webdriver.ie.driver", "./drivers/IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
driver.get(url);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
catch (Exception e)
{
int a = e.toString().indexOf("Exception:");
String str = e.toString().substring(0, a + 30);
System.out.println(str + "Exception captured");
System.err.println("The Browser Could not be Launched. Hence Failed");
}
finally
{
takeSnap();
}
return null;
}
Reporter.java:
public abstract class Reporter {
public RemoteWebDriver driver;
public ExtentHtmlReporter reporter;
public static ExtentReports extent;
public ExtentTest test;
public String testcaseName, testcaseDec, author ;
public String category="";
public static String excelFileName;
public static String extentreportpath;
#BeforeSuite (alwaysRun=true )
public void startReport(ITestContext c) throws IOException
{
String reportName=this.getClass().getName().substring(29, 33).toUpperCase() +" Screen Test Report";
String screenName=this.getClass().getName().substring(29, 33).toUpperCase() +" Tests";
String rptName="h5{font-size: 0px;}h5::after{content:\'"+screenName+"\';font-size: 1.64rem; line-height: 110%;margin: 0.82rem 0 0.656rem 0;}";
String suiteName = c.getCurrentXmlTest().getSuite().getName();
if (suiteName.contains("Default suite")||suiteName.contains("Failed suite"))
suiteName ="";
extentreportpath="./reports/"+suiteName+"Report.html";
reporter = new ExtentHtmlReporter(extentreportpath);
reporter.setAppendExisting(true);
extent = new ExtentReports();
extent.attachReporter(reporter);
reporter.loadXMLConfig(new File("./Resources/extent-config.xml"));
reporter.config().setTheme(Theme.DARK);
reporter.config().setTestViewChartLocation(ChartLocation.BOTTOM);
reporter.config().setReportName(reportName);
reporter.config().setCSS(rptName);
}
#BeforeClass(alwaysRun=true )
public ExtentTest report()
{
test = extent.createTest(testcaseName, testcaseDec);
test.assignAuthor(author);
return test;
}
public abstract long takeSnap();
public void reportStep(String desc,String status,boolean bSnap)
{
MediaEntityModelProvider img=null;
if(bSnap && !status.equalsIgnoreCase("INFO"))
{
long snapNumber=100000L;
snapNumber=takeSnap();
try
{
img=MediaEntityBuilder.createScreenCaptureFromPath("./../reports/images/"+snapNumber+".jpg").build();
}
catch(IOException e)
{
}
}
if(status.equalsIgnoreCase("pass"))
{
//test.pass(desc,img);
test.log(Status.PASS, desc, img);
}
else if(status.equalsIgnoreCase("fail"))
{
//test.fail(desc,img);
test.log(Status.FAIL, desc, img);
}
else if(status.equalsIgnoreCase("INFO"))
{
//test.pass(desc);
test.log(Status.INFO, desc,img);
}
}
public void reportStep(String desc,String status)
{
reportStep(desc,status,true);
}
#AfterSuite (alwaysRun=true )
public void stopReport() throws Exception
{
extent.flush();
}
}
Making the ExtentReport variable 'extent' as static solved my issue.
Eg: public static ExtentReports extent;
I modified the code in my question also.
Since i have only one #Test in a class, parallel="methods" is of no use in my case.
Here I am using the listener for generating reports in HTML format but it is not printing the logs present in a test case.
Sample Test Cases
#Test
public void testRedirectAllControlScreen() throws Exception {
reportLog("login using a valid IsoMetrix username and password.");
HomePage homePage = loginPage.login("username", "password");
reportLog("Go to All Control page");
AllControlPage allControlPage = homePage.navigateToControlPage();
reportLog("Verify All Control page");
allControlPage.verifyAllControlPage();
}
Method Present in BaseClass
public void reportLog(String message) {
message = BREAK_LINE + message;
logger.info("Message: " + message);
Reporter.log(message);
}
ExtentReport Listener
public class ExtentReporterNG implements IReporter {
private ExtentReports extent;
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
extent = new ExtentReports(outputDirectory + File.separator + "ExtentReport.html", true);
for (ISuite suite : suites) {
Map<String, ISuiteResult> result = suite.getResults();
for (ISuiteResult r : result.values()) {
ITestContext context = r.getTestContext();
buildTestNodes(context.getPassedTests(), LogStatus.PASS);
buildTestNodes(context.getFailedTests(), LogStatus.FAIL);
buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);
}
}
extent.flush();
extent.close();
}
private void buildTestNodes(IResultMap tests, LogStatus status) {
ExtentTest test;
if (tests.size() > 0) {
for (ITestResult result : tests.getAllResults()) {
test = extent.startTest(result.getMethod().getMethodName());
test.assignAuthor("360Log");
test.setStartedTime(getTime(result.getStartMillis()));
test.setEndedTime(getTime(result.getEndMillis()));
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
int s = result.getStatus();
if (result.getStatus() == 1) {
test.log(status, "Test " + status.toString().toLowerCase() + "ed");
} else {
String screen = BaseTest.screen;
test.log(status, "Test " + status.toString().toLowerCase() + "ed " + test.addScreenCapture(screen));
}
extent.endTest(test);
}
}
}
}
PFA the screenshot.
Without using listener I am able to achieve the same thing.
I implemented the extent test and extent report in Baseclass.java as per people suggestion like this:
public static ExtentTest test;
public static ExtentReports extent;
#BeforeSuite
public void before() {
extent = new ExtentReports("target\\surefire-reports\\ExtentReport.html", true);
}
#BeforeMethod
public void setUp(Method method) throws Exception {
test = extent.startTest(method.getClass().getSimpleName(),method.getClass().getEnclosingMethod().getName());
test.assignAuthor("Vaibhav");
//Rest code will be generic for browser initiliazion.
}
#AfterSuite
public void tearDownSuite() {
// reporter.endReport();
extent.flush();
extent.close();
}
//Method for adding logs passed from test cases
public void reportLog(String message) {
test.log(LogStatus.INFO, message);//For extentTest HTML report
logger.info("Message: " + message);
Reporter.log(message);
}
Sample Test Case
#Test
public void testRedirectAllControlScreen() throws Exception {
reportLog("login using a valid IsoMetrix username and password.");
HomePage homePage = loginPage.login("username", "password");
reportLog("Go to All Control page");
AllControlPage allControlPage = homePage.navigateToControlPage();
reportLog("Verify All Control page");
allControlPage.verifyAllControlPage();
}
ExtentReport view
The Below Code Works for me for Extent Report version : v2.41.1, Try it!!!
Try Creating an Object of Extent Report and logger as the Below Code.
// Base Class Usage
public static ExtentReports report;
public static ExtentTest logger;
report = new ExtentReports(path);
report.loadConfig(new File("//home//.....//extent-config.xml"));
logger = report.startTest(this.getClass().getSimpleName()).assignCategory("Happy Path"));
// Test Case Usage: Using it at Every Step in Each Test Case
logger.log(LogStatus.INFO,"String Message to Log for Each Step in Test Case");
// #AfterMethod
#AfterMethod(alwaysRun=true)
public void TearDown_AM(ITestResult result) throws IOException
{
System.out.println("#After Method");
try
{
if(result.getStatus()==ITestResult.FAILURE)
{
String res = captureScreenshot(Driver, result.getName());
String image= logger.addScreenCapture(res);
System.out.println(image);
String TestCaseName = this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed";
logger.log(LogStatus.FAIL, TestCaseName + logger.addScreenCapture(res));
// logger.log(LogStatus.FAIL, image, this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed");
}
else if(result.getStatus()==ITestResult.SUCCESS)
{
logger.log(LogStatus.PASS, this.getClass().getSimpleName() + " Test Case Success and Title Verified");
}
else if(result.getStatus()==ITestResult.SKIP)
{
logger.log(LogStatus.SKIP, this.getClass().getSimpleName() + " Test Case Skipped");
}
report.endTest(logger);
report.flush();
}
catch(Throwable t)
{
logger.log(LogStatus.ERROR,t.fillInStackTrace());
}
}
I know this question is little old but might help someone.
Use this code for buildTestNodes method to print TestNG logs - Reporter.log().
public void buildTestNodes(IResultMap tests, LogStatus status) {
//ExtentTest test = null;
if (tests.size() > 0) {
List<ITestResult> resultList = new LinkedList<ITestResult>(tests.getAllResults());
class ResultComparator implements Comparator<ITestResult> {
public int compare(ITestResult r1, ITestResult r2) {
return getTime(r1.getStartMillis()).compareTo(getTime(r2.getStartMillis()));
}
}
Collections.sort(resultList , new ResultComparator ());
for (ITestResult result : resultList) {
test = extent.startTest(result.getMethod().getMethodName());
test.getTest().setDescription(result.getMethod().getDescription());
test.getTest().setStartedTime(getTime(result.getStartMillis()));
test.getTest().setEndedTime(getTime(result.getEndMillis()));
for(String message:Reporter.getOutput(result)){ **//This code picks the log from Reporter object.**
test.log(LogStatus.INFO, message);
}
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
String message = "Test " + status.toString().toLowerCase() + "ed";
if (result.getThrowable() != null)
message = result.getThrowable().getClass() +": "+ result.getThrowable().getMessage();
test.log(status, message);
extent.endTest(test);
}
}
}
I am running ThreadLocal tests on a single machine. I use code in #BeforeMethod to initiate the webpage. I have also tried writing this separately as a method in my Base Test class, and calling it in #BeforeMethod.
Everything seems to work fine, except the wrong users are being logged in with the wrong tests. This is strange because the Login method is not in the BaseTest class, it is called from the Page Object (And it works fine, besides logging in the wrong user for the test).
In this example, I have included the problem code in the #BeforeMethod, and also commented out the separate "initialize" method and method call, so you can see both ways I have tried it.
public class StackExample {
protected String baseURL;
public String browser;
private static ThreadLocal<WebDriver> threadedDriver = new ThreadLocal<WebDriver>();
#BeforeMethod(alwaysRun = true)
#Parameters({ "browser", "loginType" })
public void setup(String browser, String loginType, Method caller)
throws MalformedURLException, InterruptedException {
WebDriver driver = null;
// Browsers
if (browser.equalsIgnoreCase("Internet Explorer")) {
System.setProperty("webdriver.ie.driver", "C:\\Users\\automation\\Selenium\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
} else if (browser.equalsIgnoreCase("Firefox")) {
System.setProperty("webdriver.gecko.driver", "C:\\Users\\automation\\Selenium\\geckodriver.exe");
ProfilesIni firProfiles = new ProfilesIni();
FirefoxProfile wbdrverprofile = firProfiles.getProfile("Webdriver2");
driver = new FirefoxDriver(wbdrverprofile);
} else if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\automation\\Selenium\\chromedriver.exe");
driver = new ChromeDriver();
} else if (browser.equalsIgnoreCase("MicrosoftEdge")) {
System.setProperty("webdriver.edge.driver", "C:\\Users\\automation\\Selenium\\MicrosoftWebDriver.exe");
driver = new EdgeDriver();
}
setWebDriver(driver);
this.browser = browser;
System.out.println(browser);
// initialize(loginType);
System.out.println(loginType);
if (loginType.equalsIgnoreCase("client"))
ClientReportFactory
.getTest(StringUtils.join("Client Test"), ' ') + " ("
+ browser + ")", "This test is located in class: " + getClass().getName());
else if (loginType.equalsIgnoreCase("advisor"))
AdvisorReportFactory
.getTest(StringUtils.join("Advisor Test"), ' ') + " ("
+ browser + ")", "This test is located in class: " + getClass().getName());
if (loginType.equalsIgnoreCase("client"))
baseURL = "ClientWebsite.example";
else if (loginType.equalsIgnoreCase("advisor"))
baseURL = "AdvisorWebsite.example";
else {
System.out.println("Client or Advisor must be specified in TestNG XML");
}
driver.get(baseURL);
driver.manage().window().maximize();
}
// public void initialize(String loginType) throws InterruptedException {
// if (loginType.equalsIgnoreCase("client"))
// baseURL = "ClientWebsite.example";
// else if (loginType.equalsIgnoreCase("advisor"))
// baseURL = "AdvisorWebsite.example";
// else{
// System.out.println("Client or Advisor must be specified in TestNG XML");
// }
// driver.get(baseURL);
// driver.manage().window().maximize();
//
// }
public static WebDriver getDriver() {
return threadedDriver.get();
}
static void setWebDriver(WebDriver driver) {
threadedDriver.set(driver);
}
#AfterMethod // (alwaysRun = true)
#Parameters({ "loginType" })
public void afterMethod(Method caller, String loginType) {
// Here we are making sure we close the same test we opened.
System.out.println(loginType);
if (loginType.equalsIgnoreCase("client"))
ClientReportFactory
.closeTest(StringUtils.join("Client Test"), ' ') + " ("
+ browser + ")");
else if (loginType.equalsIgnoreCase("advisor"))
AdvisorReportFactory
.closeTest(StringUtils.join("Advisor Test"), ' ') + " ("
+ browser + ")");
getDriver().quit();
threadedDriver.set(null);
}
#AfterSuite
#Parameters({ "loginType" })
public void afterSuite(String loginType) {
if (loginType.equalsIgnoreCase("client"))
ClientReportFactory.closeReport();
else if (loginType.equalsIgnoreCase("advisor"))
AdvisorReportFactory.closeReport();
if (getDriver() != null) {
getDriver().quit();
} else {
System.out.println("Drivers already closed");
}
}
}
Here are my test methods. They call the actual SignIn method from their page objects. I know this isn't the problem because all other methods called from the page object are working fine with the correct test.
public class StackExampleTests extends StackExample {
#Test(enabled = true, priority = 0)
public void ClientTest1() throws Exception {
ExtentTest t = ClientReportFactory.getTest();
t.log(LogStatus.INFO, "Client 1 Login for " + browser);
try {
Login objLogin = new Login(getDriver());
String username = "username1";
String password = "password1";
t.log(LogStatus.INFO, "Logging in as user: " + username);
objLogin.SignIn(username, password);
// perform First Client's tests here
} catch (Exception e) {
t.log(LogStatus.WARNING, "Exception found: " + e.getMessage().substring(0, 400)
+ t.addBase64ScreenShot(ClientReportFactory.CaptureScreen(getDriver())));
}
}
#Test(enabled = true, priority = 1)
public void ClientTest2 throws Exception{
ExtentTest t = ClientReportFactory.getTest();
t.log(LogStatus.INFO, "Client 2 Login for " + browser);
try {
Login objLogin = new Login(getDriver());
String username = "username2";
String password = "password2";
t.log(LogStatus.INFO, "Logging in as user: " + username);
objLogin.SignIn(username, password);
// perform Second Client's tests here
} catch (Exception e) {
t.log(LogStatus.WARNING, "Exception found: " + e.getMessage().substring(0, 400)
+ t.addBase64ScreenShot(ClientReportFactory.CaptureScreen(getDriver())));
}
}
}
I think this trace means that it is starting all 3 of my tests in the same thread. But I'm not completely
Starting ChromeDriver 2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9) on port 44694
Only local connections are allowed.
Starting ChromeDriver 2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9) on port 12513
Only local connections are allowed.
Starting ChromeDriver 2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9) on port 32651
Only local connections are allowed.
It looks like your tests are having a driver identity crisis with which WebDriver belongs to them when running in parallel locally.
Setting ThreadLocal<WebDriver> threadedDriver, getDriver(), and setDriver() to not static should fix the problem.
i am Unable to Have separate Logs/entries for Different Test Cases. i.e Logs are Getting Appended on to a Single Test Case in the Extent Report generated.
Using Extent Report Version 2.41.1..
The Report Sample:
MY Code Goes like This:
Base Class of TestNG:
public static ExtentReports report;
public static ExtentTest logger;
#BeforeSuite
#Parameters({"BrowserName"})
public void beforeSuite(#Optional("Firefox") String BrowserName)
{
date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("dd-MM-yyyy");
String TodaysDate = ft.format(date);
prop = ResourceBundle.getBundle("DataFile");
Driver = Browser_Factory_FSQA_Class.getBrowser(BrowserName);
path = "//home//workspace//....//FSQA.ExtentReports//FSQA_ExtentReport_" + TodaysDate;
File f=new File(path);
if(!f.exists())
{
report = new ExtentReports(path);
}
}
#BeforeTest
#Parameters({"BrowserName"})
public void SetUpConfig(#Optional("Firefox") String BrowserName)
{
report = new ExtentReports(path, false,DisplayOrder.NEWEST_FIRST);
report.loadConfig(new File("//home//......//extent-config.xml"));
report.addSystemInfo("Build-Tag", prop.getString("Build-Tag"))
.addSystemInfo("Selenium ", prop.getString("SelVer"))
.assignProject(prop.getString("Application"))
.addSystemInfo("Envirnoment", prop.getString("AppEnvirnoment"))
.addSystemInfo("Extent", prop.getString("ExtRpVer"));
logger = report.startTest(this.getClass().getSimpleName());
logger.log(LogStatus.INFO,this.getClass().getSimpleName() +" will Run on "+ BrowserName +" Browser");
Driver.get(prop.getString("URL"));
Driver.manage().window().maximize();
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
}
#AfterMethod(alwaysRun=true)
public void afterMethod(ITestResult result) throws IOException
{
try
{
if(result.getStatus()==ITestResult.FAILURE)
{
String res = captureScreenshot(Driver, result.getName());
String image= logger.addScreenCapture(res);
System.out.println(image);
String TestCaseName = this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed";
logger.log(LogStatus.FAIL, TestCaseName + logger.addScreenCapture(res));
}
else if(result.getStatus()==ITestResult.SUCCESS)
{
logger.log(LogStatus.PASS, this.getClass().getSimpleName() + " Test Case Success and Title Verified");
}
else if(result.getStatus()==ITestResult.SKIP)
{
logger.log(LogStatus.SKIP, this.getClass().getSimpleName() + " Test Case Skipped");
}
}
catch(Throwable t)
{
logger.log(LogStatus.ERROR,t.getMessage());
}
}
public String captureScreenshot(WebDriver Driver, String TestName)
{
try
{
date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("dd_MM_yyyy");
String TodaysDate = ft.format(date);
TakesScreenshot ts=(TakesScreenshot)Driver;
File source=ts.getScreenshotAs(OutputType.FILE);
Sc_Destination = prop.getString("SC_Dest")+TestName+"__"+TodaysDate+".png";
FileUtils.copyFile(source,new File(Sc_Destination));
logger.log(LogStatus.FAIL,image, "Title verification");*/
return Sc_Destination;
}
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
}
return Sc_Destination;
}
#AfterTest(alwaysRun=true)
public void AfterTest()
{
Driver.close();
report.endTest(logger);
report.flush();
}
#AfterSuite
public void AfterSuite()
{
report.close();
Driver.quit();
}
My Tests are Separate Clases which Extends this Base Class:
TC1:
public classTC1 extends BaseTestNG
{
#Test(groups = {"Happy_Path"} , description="TC1")
public void TestCase1() throws InterruptedException, Exception
{
logger.log(LogStatus.INFO, " Test Case2 Block Entered");
Thread.sleep(4000);
......
......
logger.log(LogStatus.INFO, "Assert Flag Received");
Thread.sleep(4000);
Assert.assertTrue(AssertFlag);
}
}
TC2:
public classTC2 extends BaseTestNG
{
#Test(groups = {"Happy_Path"} , description="TC2")
public void TestCase2() throws InterruptedException, Exception
{
logger.log(LogStatus.INFO, " Test Case2 Block Entered");
Thread.sleep(4000);
......
......
logger.log(LogStatus.INFO, "Assert Flag Received");
Thread.sleep(4000);
Assert.assertTrue(AssertFlag);
}
}
I am Using POM Classes along with TestNG and running the Testcases using testng.xml.
I am able to generate the Extent Report but unable to Differentiate Between TC1 & TC2 Logs i.e all test Case logs are getting appended to single TestCase as shown in the Above Screen Shot.
I want each Test Case Logs/Entry in separate rows in the Extent Reports.
Can Anyone please rectify the mistake in my code and help me out.
Thanks in Advance!!!
I think, you should initialize your logger in BeforeMethod and use report.flush() in AfterMethod. That may solve your problem.
Beginner in this space, appreciate your help on the problem!
I'm trying to script a path
Login
create new user
log out
Login method works fine
Create user is dependent on Login method to be completed, using data providers and post login to create new user
Issue is after logging in the elements/objects in create user class are not identified. I have tried it using different element finders and browsers. Appreciate if you help around
Project Structure is
Project
Package1
Logindataprovider.class
newaccountDataProvider.class
Package2
LoginpageObjects.class
NewAccountPageObjects.class
Package3
LoginTestscripts.class
NewAccountTestScript.class
LoginTestscripts- Class
LoginPageObjects LgnObj = new LoginPageObjects();
#Test(groups = { "Logingroup1" }, dataProvider = "LoginCred", dataProviderClass = LoginDataProviders.class)
public void mytest(String DDUname, String DDpwd,String ExpLoginPage, int Browsertype) {
LgnObj.setBrowser(Browsertype);
Logger log = Logger.getLogger(LoginDataProviders.class);
log.info("Login To application method");
LgnObj.init();
// Login page assertion actual values
String LoginPageAssertactual = LgnObj.LoginPageAssertionActual();
//Login page assertion
Assert.assertEquals(LoginPageAssertactual, ExpLoginPage);
//login to application
LogginCommonProcess(DDUname, DDpwd, LgnObj);
}
public void LogginCommonProcess(String DDUname, String DDpwd,
LoginPageObjects LgnObj) {
LgnObj.enterUserName(DDUname);
LgnObj.enterPassword(DDpwd);
LgnObj.Loginbtn();
LgnObj.enterPIN();
LgnObj.CompanyName();
}
Logindataprovider- Class
public class LoginPageObjects {
WebDriver driver;
public void setBrowser(int type) {
if (type == 1) {
driver = new FirefoxDriver();
} else if (type == 2) {
String path = ClassLoader.getSystemResource("chromedriver.exe")
.getPath();
System.setProperty("webdriver.chrome.driver", path);
driver = new ChromeDriver();
} else if (type == 3) {
String path = ClassLoader.getSystemResource("IEDriverServer.exe")
.getPath();
System.setProperty("webdriver.ie.driver", path);
driver = new InternetExplorerDriver();
}
}
public void init() {
driver.manage().window().maximize();
driver.navigate().to("https://test2.qatest.com/Login.aspx");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
public String LoginPageAssertionActual() {
String LoginPageAssertionact = driver.findElement(By.tagName("h1"))
.getText();
return LoginPageAssertionact;
}
public void enterUserName(String DDUname) {
driver.findElement(By.id("ctl00_MainContent_usernameField")).sendKeys(
DDUname);
}
public void enterPassword(String DDpwd) {
driver.findElement(By.id("ctl00_MainContent_passwordField")).sendKeys(
DDpwd);
}
New User- page object
public class NewUser {
WebDriver driver;
public void setup() {
System.out.println("Start here");
System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.navigate().to("https://test2.directorsdesk.com/Login.aspx");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
public void setBrowser(int type) {
if (type == 1) {
driver = new FirefoxDriver();
} else if (type == 2) {
String path = ClassLoader.getSystemResource("chromedriver.exe")
.getPath();
System.setProperty("webdriver.chrome.driver", path);
driver = new ChromeDriver();
} else if (type == 3) {
String path = ClassLoader.getSystemResource("IEDriverServer.exe")
.getPath();
System.setProperty("webdriver.ie.driver", path);
driver = new InternetExplorerDriver();
} else if (type == 4) {
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setVersion("38");
cap.setPlatform(Platform.WINDOWS);
try {
driver = new RemoteWebDriver(new URL(
"http://127.0.0.1:4444/wd/hub"), cap);
} catch (MalformedURLException e) {
// log erro unable to access remote system, running in local
// firefox
driver = new FirefoxDriver();
}
}
}
**public void ManageSystem() {
driver.findElement(By.partialLinkText("Manage System")).click();
driver.findElement(By.linkText("Manage System")).click();
}**
public class NewAccount {
#Test(dataProvider = "UserDetails", dataProviderClass = LoginDataProviders.class, dependsOnGroups = "Logingroup1")
public void CreateNewAccount(String Emailid, String Firstname,
String Lastname, String PrimaryEmailid, int browserType) {
NewUser NewUserObj = new NewUser();
NewUserObj.setBrowser(browserType);
**NewUserObj.ManageSystem();** // Fails here
NewUserObj.UserAccounts();
NewUserObj.NewUserAccount();
NewUserObj.Emailid(Emailid);
NewUserObj.UserFirstname(Firstname);
NewUserObj.UserLastname(Lastname);
NewUserObj.PrimaryEmai(PrimaryEmailid);
NewUserObj.SaveAccountSettings();
LoginPageObjects LgnPgObj = new LoginPageObjects();
LgnPgObj.Logout();
LgnPgObj.closeBrowser();
}
Have you tried this:
public void entityFieldIsEntered(String field, String value) {
WebElement valueElem = new SharedDriver().findElement(By.xpath("(.//*[text()='" + field
+ ":'])[2]/parent::*/span/input"));
valueElem.sendKeys(new CharSequence[] { value });
}
assuming you are using input wrapper in your html. This code search for text label on the screen, then goes to its parent and navigate to input field.
If you are going to use multiple page objects in one test, you will need to share the same driver between those page objects.
Try creating a separate setupDriver class and have each page object take a driver parameter to be constructed.
At the beginning of each test setup the driver, then pass in the driver as you create each object.