BaseTest class doesn't initialize the Webdriver instance - selenium-webdriver

I have gone through similar type Q&As, but couldn't figure out the issue in my code.
This is my BaseTest class
`
package com.supportiveTests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.cucumber.java.After;
import io.cucumber.java.Before;
public class BaseTests {
public static WebDriver driver;
#Before
public void setUpDriver() {
System.setProperty("webdriver.chrome.driver", "src/main/resources/Drivers/chromedriver.exe");
driver = new ChromeDriver();
}
#After
public void quitDriver() {
this.driver.quit();
System.out.println("done AfterTest");
}
}
`
This is my stepDefinition class (LoginPageSteps)
`
package com.stepDefinitions;
import com.pageObjects.LoginPage;
import com.supportiveTests.BaseTests;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.testng.annotations.Test;
#Test
public class LoginPageSteps extends BaseTests {
LoginPage obj_login;
#Given("User is on Google Home page")
public void user_is_on_google_home_page() {
BaseTests.driver.navigate().to("https://www.google.com/");
}
#Given("User is navigated to SwagLabs Login page")
public void user_is_navigated_to_swag_labs_login_page() {
BaseTests.driver.navigate().to("https://www.saucedemo.com/");
}
#When("^User enters valid (.*) and (.*)$")
public void user_enters_valid_standard_user_and_secret_sauce(String username, String password) {
obj_login = new LoginPage(driver);
obj_login.enterUserName(username);
obj_login.enterPassword(password);
}
#When("clicks on LOGIN button")
public void clicks_on_login_button() {
obj_login.clickOnLogin();
}
#Then("User is navigated to SwagLAbs Home page")
public void user_is_navigated_to_swag_l_abs_home_page() throws InterruptedException {
BaseTests.driver.getCurrentUrl().contains("https://www.saucedemo.com/inventory.html");
Thread.sleep(2000);
BaseTests.driver.quit();
}
}
`
This is my TestRunner class
`
package com.supportiveTests;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;
#RunWith(Cucumber.class)
#CucumberOptions(features = "src/test/Features",
glue = {"com/stepDefinitions"},
monochrome = true,
plugin = {
"pretty", "html:target/HTMLReports/report.html",
"json:target/JSONReports/report.json",
"junit:target/JUnitReports/report.xml"
}
)
public class TestRunner {
}
`
This is my pageObject class (LoginPage)
`
package com.pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
WebDriver driver;
public LoginPage(WebDriver driver) {
this.driver = driver;
}
By txt_username = By.xpath("//input[#id='user-name']");
By txt_password = By.xpath("//input[#id='password']");
By btn_login = By.xpath("//input[#id='login-button']");
public void enterUserName(String username){
driver.findElement(txt_username).sendKeys(username);
}
public void enterPassword(String password){
driver.findElement(txt_password).sendKeys(password);
}
public void clickOnLogin(){
driver.findElement(btn_login).click();
}
}
When the above TestRunner class is executed, I get this error
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.navigate()" because "com.supportiveTests.BaseTests.driver" is null
at com.stepDefinitions.LoginPageSteps.user_is_on_google_home_page(LoginPageSteps.java:16)
I went through the similar Q&As, where the solutions for driver initialization were provided, but couldn't figure out the issue. I am at basic level of Selenium testing framework, so appreciate any guidance on fixing this.

Related

How to define actions in page object modeling

I am newbee to selenium. I was trying to access menu->sub-menu in PageObject Modeling.
My requirement is to click on Menu item and sub-menu item which appears dynamically.
I was going through StackOverflow and in one of the resolutions it was mentioned to write Actions as
Actions actions = new Actions(driver);
actions.moveToElement(currentOpenings).build().perform();
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.elementToBeClickable(ausJobsSubmenu));
However i can't pass driver in constructor. if I pass constructor i am getting problem while running this script. The error is below
FAILED: checkLinks java.lang.Error: Unresolved compilation problem:
The method HomePageLinksClick(WebDriver) in the type HomePageLinksTest is not applicable for the arguments ()
If I include WebDriver driver in constructor as a parameter, my page class is not accepting that as parameter. Can anyone help?
Page Class
package au.com.sreetechconsulting.Pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import au.com.sreetechconsulting.TestCases.HomePageLinksTest;
public class HomePage {
public WebDriver driver;
#BeforeTest
public void openBrowser() {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.sreetechconsulting.com.au/");
}
#Test
public void checkLinks() {
HomePageLinksTest linkClick = new HomePageLinksTest(driver);
linkClick.HomePageLinksClick();
}
}
Test Page Class
package au.com.sreetechconsulting.TestCases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class HomePageLinksTest {
#FindBy(css="#header > div.container > div > div.col-md-9.main-nav > nav > ul > li:nth-child(2) > a")
private WebElement currentOpenings;
#FindBy(css="#header > div.container > div > div.col-md-9.main-nav > nav > ul > li:nth-child(2) > ul > li:nth-child(1) > a")
private WebElement ausJobsSubmenu;
public HomePageLinksTest (WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void HomePageLinksClick() {
//currentOpenings.click();
Actions actions = new Actions(driver);
actions.moveToElement(currentOpenings).build().perform();
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.elementToBeClickable(ausJobsSubmenu));
}
}
You can keep the driver as a class member from the constructor
public class HomePageLinksTest {
private WebDriver driver;
public HomePageLinksTest (WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void HomePageLinksClick() {
//currentOpenings.click();
Actions actions = new Actions(driver);
actions.moveToElement(currentOpenings).build().perform();
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.elementToBeClickable(ausJobsSubmenu));
}
}
And in the test use it like this
#Test
public void checkLinks() {
HomePageLinksTest linkClick = new HomePageLinksTest(driver);
linkClick.HomePageLinksClick();
}

Error when executing testng.xml using pagefactory

I am running 2 classes using testNG.First class is running successfully but second class is failing with error:
"org.testng.TestNGException:Can't invoke public void TestScripts.NewAccountCreation.AccountCreation1(): either make it static or add a no-args constructor to your class"
If I add non argument constructor I am getting null pointer exception.
I am using Pagefactory to design my test cases.
Eclipse version:kepler
TestnG:6.9.9
Chrome version: 57.0.2987.133
Chrome driver: 2.27
Any suggestions would be greatly appreciated.
Please find the below code:
Page factory Code for Login Page:
/**
*
*/
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import Pages.LoginPage;
public class LoginPage {
WebDriver driver;
public LoginPage(WebDriver ldriver)
{
this.driver = ldriver;
}
#FindBy(xpath = "//input[contains(#id,'username-inputEl')]")
public WebElement username;
#FindBy(xpath = "//input[contains(#id,'password-inputEl')]")
public WebElement password;
#FindBy(xpath = "//span[contains(#id,'submit-btnInnerEl')]")
public WebElement LoginButton;
// Methods to perform actions
public void pCLogin(String Username, String Password, WebDriver driver)
{
username.sendKeys(Username);
password.sendKeys(Password);
LoginButton.click();
}
}
Page Factory code for Account creation page:
package Pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Accounttab {
WebDriver driver;
public Accounttab(WebDriver ldriver)
{
this.driver = ldriver;
}
#FindBy(xpath = "//span[#id='TabBar:AccountTab-btnWrap']")
public WebElement accountDropDown;
#FindBy(xpath = "//span[contains(#id,'AccountTab_NewAccount-textEl')]")
public WebElement NewAccount_Button;
#FindBy(xpath = "//textarea[contains(#id,'GlobalContactNameInputSet:Name-inputEl')]")
public WebElement Companyname;
#FindBy(xpath = "//input[contains(#id,'OfficialIDDV_Input-inputEl')]")
public WebElement FEINNumber;
#FindBy(xpath = "//input[contains(#id,'GlobalAddressInputSet:City-inputEl')]")
public WebElement City;
#FindBy(xpath = "//input[contains(#id,'GlobalAddressInputSet:PostalCode-inputEl')]")
public WebElement Zipcode;
#FindBy(xpath = "//a[contains(#id,'SearchLinksInputSet:Search')]")
public WebElement AccountsearchButton;
#FindBy(xpath = "//span[#class='x-btn-inner x-btn-inner-center'][contains(#id,'NewAccountButton-btnInnerEl')]")
public WebElement CreateNewButton;
#FindBy(css = "input[id='TabBar:AccountTab:AccountTab_AccountNumberSearchItem-inputEl']")
public WebElement AccountSearch;
#FindBy(xpath = "//tbody[contains(#id,'gridview')]//tr[1]//td[2]")
public WebElement SelectAccountNumber;
public void accountMouseHover(WebDriver driver) {
WebDriverWait wait1 = new WebDriverWait(driver, 10);
wait1.until(ExpectedConditions.visibilityOf(accountDropDown));
Actions builder2 = new Actions(driver);
builder2.moveToElement(accountDropDown).moveByOffset(50, 0).click()
.build().perform();
System.out.println("Dropdown is opened");
}
public void accountSearch(String AccountName, WebDriver driver)
{
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions .visibilityOf(NewAccount_Button));
driver.manage().window().maximize();
Actions builder1 = new Actions(driver);
builder1.moveToElement(NewAccount_Button).click().build().perform();
System.out.println("Clicked on New Accounr Button");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Companyname.sendKeys(AccountName);
try {
AccountsearchButton.click();
} catch (Exception e) {
System.out
.println("Please enter one of the minimum required fields: Company Name, FEIN"
+ e);
throw (e);
}
wait.until(ExpectedConditions .visibilityOf(CreateNewButton));
CreateNewButton.click();
}
}
Test Scripts1:
LoginClass:
**
package TestScripts;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import Pages.LoginPage;
import Utility.Configreader;
import Utility.GenericMethods;
public class Login {
WebDriver driver;
LoginPage Login_page;
#BeforeSuite
public void setUp() {
Configreader cr = new Configreader(
"H://Selenium//Selenium_ODSRegression//TestData//config.properties");
driver = GenericMethods.startBrowser("Chrome", cr.getURL());
Login_page = PageFactory.initElements(driver, LoginPage.class);
}
#Test
public void PClogin() {
Login_page.pCLogin("su", "gw", driver);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
}
**
Test Script2:
AccountCreation class:
package TestScripts;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import Pages.AccountFileSummary;
import Pages.Accounttab;
import Pages.CreateNewAccount;
public class NewAccountCreation {
WebDriver driver;
Accounttab Account_tab1;
CreateNewAccount NewAccount1;
AccountFileSummary AFS1;
public NewAccountCreation(WebDriver ldriver)
{
this.driver = ldriver;
Account_tab1 = PageFactory.initElements(driver, Accounttab.class);
}
#Test
public void AccountCreation1() {
Account_tab1.accountMouseHover(driver);
Account_tab1.accountSearch("WebDriver_Test1", driver);
}
}
driver class:
package Utility;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import Utility.Configreader;
public class GenericMethods {
public static WebDriver driver = null;
static Configreader cr = new Configreader(
"H://Selenium//Selenium_ODSRegression//TestData//config.properties");
public static WebDriver startBrowser(String browsername, String URL)
{
if (browsername.equalsIgnoreCase("Chrome"))
{
System.setProperty("webdriver.chrome.driver",
cr.getChromeDriverPath());
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("--js-flags=--expose-gc");
options.addArguments("--enable-precise-memory-info");
options.addArguments("--disable-popup-blocking");
options.addArguments("--disable-default-apps");
options.addArguments("test-type=browser");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
else if (browsername.equalsIgnoreCase("IE"))
{
System.setProperty("webdriver.ie.driver", cr.getIEDriverPath());
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
}
driver.get(URL);
return driver;
}
}
Property file:
PCURL = http://biltipolicycenter.thehartford.com/pc/PolicyCenter.do
ChromeBrowserPath = C://Selenium//ChromeDriver 2.27//chromedriver.exe
IEBrowserPath = C://Selenium//IEDriverServer x86 2.53//IEDriverServer.exe
TestNG.XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class name="TestScripts.Login"/>
<class name="TestScripts.NewAccountCreation"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
NewAccountCreation is a test class because it contains test method(s) and because you declare it as a class test in the testng.xml.
So, it means TestNG must be able to create an instance of the class and that's why TestNG is complaining.
You have 2 options:
Using a factory to explain to TestNG how to create test classes
(best option IMO)
Using a static shared driver instance (Login#driver is not
yet static)
BTW, your organization of classes looks a bit dirty and you should rework them a bit.

the method get(class <ReportClass>) is undefined for the type ExtentReport

i'm making selenium extent report but i'm getting error on - static final ExtentReports extrpt=ExtentReports.get(ReportClass.class);
after mouse hover on get i'm getting below info.
the method get(class ) is undefined for the type ExtentReports
it's my simple java project please tell me where am i doing mistake.
package DemoPacakge;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
public class ReportClass {
// * ReportClass .class will become TheClassName.class
static final ExtentReports extrpt=ExtentReports.get(ReportClass.class);
public void test()
{
WebDriver driver =new FirefoxDriver();
driver.get("http://learn-automation.com/advance-selenium-reporting-with-screenshots/");
String tile=driver.getTitle();
Assert.assertTrue(tile.contains("learn"));
}
}
Please see the examples section: http://extentreports.relevantcodes.com/1x/docs.html#examples
There are a few errors such as, you are not initializing the report with a "file-path". You have not instructed Extent to start a test either. Try with the below code, it should work:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.LogStatus;
public class ReportClass {
static final ExtentReports extrpt = ExtentReports.get(ReportClass.class);
WebDriver driver;
#BeforeClass
public void beforeClass() {
extrpt.init("file-path.html", true);
extrpt.config().displayCallerClass(false);
}
#Test
public void test() {
extrpt.startTest("Test");
driver = new FirefoxDriver();
extrpt.log(LogStatus.INFO, "Starting FirefoxDriver..");
driver.get("http://learn-automation.com/advance-selenium-reporting-with-screenshots/");
extrpt.log(LogStatus.INFO, "Navigating to learn-automation.com..");
String title = driver.getTitle();
extrpt.log(LogStatus.INFO, "Title: " + title);
try {
Assert.assertTrue(title.contains("learn"));
extrpt.log(LogStatus.PASS, "Step Passed");
}
catch (AssertionError e) {
extrpt.log(LogStatus.FAIL, "<pre>" + e.getMessage() + "</pre>");
}
}
#AfterTest
public void afterTest() {
driver.quit();
extrpt.endTest();
}
}

Runing test cases in all browser one after another

I want to run selenium webdriver test cases in all multiple browser but not in parallel.Is it possible to run test cases in all multiple browser without using xml and selenium grid.Can we do it by using annotation and java classes.I wanted that my test cases should execute in firefox first and after completion of execution in firefox it should start execution in chrome and so on.
I have tried this code to execute my test cases from one browser to another but not simultaneously.but it throw exceptions.
ManyBrowsers.java
import java.io.File;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ManyBrowsers implements MethodRule {
public static WebDriver driver;
#Override
public Statement apply(final Statement base, FrameworkMethod method, Object target) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
//RUN FIREFOX
driver = new FirefoxDriver();
base.evaluate();
driver.quit();
//RUN CHROME
File f = new File("D:\\SeleniumTestCases\\Selenium_Drivers\\chromedriver" ) ;//PATH to CHROME DRIVER
System.setProperty("webdriver.chrome.driver", f.getAbsolutePath());
driver = new ChromeDriver();
base.evaluate();
driver.quit();
}
};
}
}
Example Test
import java.util.concurrent.TimeUnit;
import org.junit.Rule;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.annotations.AfterClass;
import com.thoughtworks.selenium.webdriven.commands.WaitForPageToLoad;
public class TestClass1 {
protected static WebDriver driver;
protected static String result;
#Rule
public ManyBrowsers browsers = new ManyBrowsers();
#BeforeClass
public static void setup() {
ManyBrowsers.driver.navigate().to("http://www.floraindia.com");
}
#Test
void Testcase1() {
System.out.println("Testcase1");
driver.findElement(By.id("kwsch")).sendKeys("Red");
driver.findElement(By.xpath("//input[#src='image/go.gif']")).click();
}
#Test
public void testGmail() throws Exception {
driver.get("http://www.gmail.com");
driver.findElement(By.id("Email")).clear();
driver.findElement(By.id("Email")).sendKeys("testemail");
driver.findElement(By.id("Passwd")).clear();
driver.findElement(By.id("Passwd")).sendKeys("123456");
driver.findElement(By.id("signIn")).click();
}
#AfterClass
public static void teardown() {
driver.close();
driver.quit();
}
Create different classes for the different tests in different browsers. For example:
First class:
public class FirefoxTest
{
WebDriver driver;
#BeforeClass
public void beforeClass() {
this.driver = new FirefoxDriver();
}
#Test
public void test() {
this.driver.get("http://google.com");
}
#AfterClass
public void afterClass() {
this.driver.quit();
}
}
Second class:
public class ChromeTest
{
WebDriver driver;
#BeforeClass
public void beforeClass() {
this.driver = new ChromeDriver();
}
#Test
public void test() {
this.driver.get("http://google.com");
}
#AfterClass
public void afterClass() {
this.driver.quit();
}
}
If you run your project as a TestNG Test, it will create your xml file programatically which will include all of the classes, so in this case you don't have to create it manually.
You get NullPointerException because method evaluate from class ManyBrowsers is invoked only before #Test methods.
You should use class ManyBrowsers only in methods with #Test annotation.

Selenium Web driver--Failure Screenshot is not captured in TestNG report

With below mentioned code,if the test case is pass-screenshot captured successfully and displayed in report.But when the test is failed--screenshot is not displayed.Even screenshot hyperlink is not displayed in report.Anybody can sort out the mistake in code?
package listeners;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import java.util.logging.Logger;
#Listeners
public class CountryChoserLayer extends TestListenerAdapter {
#Test(priority=1)
public void choseCountry() throws Exception{
driver.findElement(By.id("intselect")).sendKeys("India");
driver.findElement(By.xpath(".//*[#id='countryChooser']/a/img")).click();
//window.onbeforeunload = null;
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
FileUtils.copyFile(scrnsht, new File(NewFileNamePath));
System.out.println(NewFileNamePath);
Reporter.log("Passed Screenshot");
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case-Success");
System.out.println("---------------------------------------");
}
public String baseurl="http://www.sears.com/shc/s/CountryChooserView?storeId=10153&catalogId=12605";
public WebDriver driver;
public int Count = 0;
#Test(priority=0)
public void openBrowser() {
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.get(baseurl);
}
#Test(priority=2)
public void closeBrowser() {
driver.quit();
}
#Override
public void onTestFailure(ITestResult result){
Reporter.log("Fail");
System.out.println("BBB");
//Reporter.setCurrentTestResult(result);
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//File scrFile = ((TakesScreenshot) WebDriver.globalDriverInstance).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
//System.out.println("AAA" + NewFileNamePath);
try {
//System.out.println("CCC");
FileUtils.copyFile(scrnsht,new File(NewFileNamePath));
System.out.println(NewFileNamePath);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("DDD");
e.printStackTrace();
}
Reporter.log("Failed Screenshot");
Reporter.setCurrentTestResult(null);
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case Failed");
System.out.println("---------------------------------------");
}
#Override
public void onTestSkipped(ITestResult result) {
// will be called after test will be skipped
Reporter.log("Skip");
}
#Override
public void onTestSuccess(ITestResult result) {
// will be called after test will pass
Reporter.log("Pass");
}
}
Your onTestFailure method is not being called because you didn't specify listener for your test class. You are missing a value in #Listeners annotation. It should be something like
#Listeners({CountryChoserLayer.class})
You can find more ways of specifying a listener in official TestNg's documentation.
Another problem you are likely to encounter would be NullPointerException while trying to take screenshot in onTestFailure method. The easiest workaround for that would be changing the declaration of driver field to static. I run the code with those fixes and I got the report with screenshot.
I must add that in my opinion putting both test and listener methods into one class is not a good practice.

Resources