How to use Extent Report logs in Page Objects? - selenium

I am getting Null Pointer Exception when using the test.log() method into Page Objects.
My Extent Report test is defined in the "#BeforeMethod" at the TestBase class. Hence, I need to access the test.log(); into the Page Object e.g. LoginPage.java. It's works fine at the test case level i.e. LoginPageTest.java
#BeforeMethod
public void beforeMethod(Method method) {
String testMethodName = method.getName();
test = extent.createTest(testMethodName);
String testReslt = method.getName();
test.info(MarkupHelper.createLabel(testReslt, ExtentColor.BLUE));
log.info("**************" + method.getName() + "Started***************");
}
public static void logExtentReport(String str) {
test.log(Status.INFO, str);
}
Below is the LoginPage.java (which is a page-object class)
public class LoginPage {
private WebDriver driver;
private final Logger log = LoggerHelper.getLogger(LoginPage.class);
VerificationHelper verificationHelper;
WaitHelper waitHelper;
#FindBy(css = "#email")
WebElement loginEmail;
#FindBy(css = "#password")
WebElement loginPassword;
#FindBy(css = "#loginbutton")
WebElement loginBtn;
#FindBy(css = "#loginerrormsg")
WebElement authenticationFailureMessage;
#FindBy(css = "#soflow-color")
WebElement userProfileDrpDwn;
#FindBy(xpath = "//option[#value='string:logout']")
WebElement logout;
#FindBy(tagName = "a")
List<WebElement> allLinks;
String urls[] = null;
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
waitHelper = new WaitHelper(driver);
waitHelper.waitForElement(loginBtn,
ObjectReader.reader.getExplicitWait());
}
public void enterEmailAddress(String emailAddress) {
log.info("entering email address...." + emailAddress);
this.loginEmail.clear();
this.loginEmail.sendKeys(emailAddress);
}
public void enterPassword(String password) {
log.info("entering password...." + password);
this.loginPassword.clear();
this.loginPassword.sendKeys(password);
}
public ProspectorPage clickOnSubmitButton(String isValidCredentials) {
log.info("clicking on submit button...");
loginBtn.click();
if (isValidCredentials.equalsIgnoreCase("yes")) {
return new ProspectorPage(driver);
}
return null;
}
public boolean verifySuccessLoginMsg() {
return new VerificationHelper(driver).isDisplayed(userProfileDrpDwn);
}
public boolean verifyAuthenticationFailureMsg() {
return new
VerificationHelper(driver).isDisplayed(authenticationFailureMessage);
}
public void loginToApplication(String emailAddress, String password,
String isValidCredentials) {
enterEmailAddress(emailAddress);
loginBtn.click();
enterPassword(password);
new TestBase().captureScreen("Login Page_1", driver);
clickOnSubmitButton(isValidCredentials);
}
public void logout() {
userProfileDrpDwn.click();
new TestBase().captureScreen("Logout", driver);
waitHelper.waitForElement(logout,
ObjectReader.reader.getExplicitWait());
logout.click();
log.info("clicked on logout link");
TestBase.logExtentReport("clicked on logout link");
waitHelper.waitForElement(loginBtn,
ObjectReader.reader.getExplicitWait());
}
}
}
As you can see in the LoginPage class, I have used TestBase.logExtentReport() method, which is showing NullPointerException, and I cannot initialize the TestBase reference in the PageObject class. Hence, How can I use the logExtentReport method there?
Helper Class is also getting NPE, even after changing the scope of logger from final to static. Below is the code:
import com.uiFramework.engie.prospector.helper.logger.LoggerHelper;
import com.uiFramework.engie.prospector.testbase.TestBase;
public class VerificationHelper {
private WebDriver driver;
private static Logger log =
LoggerHelper.getLogger(VerificationHelper.class);
public VerificationHelper(WebDriver driver){
this.driver = driver;
}
public boolean isDisplayed(WebElement element){
try{
element.isDisplayed();
log.info("element is Displayed.."+element.getText());
TestBase.logExtentReport("element is
Displayed.."+element.getText());
return true;
}
catch(Exception e){
log.error("element is not Displayed..", e.getCause());
TestBase.logExtentReport("element is not
Displayed.."+e.getMessage());
return false;
}
}
public boolean isNotDisplayed(WebElement element){
try{
element.isDisplayed();
log.info("element is present.."+element.getText());
TestBase.logExtentReport("element is
present.."+element.getText());
return false;
}
catch(Exception e){
log.error("element is not present..");
return true;
}
}
public String readValueFromElement(WebElement element){
if(null == element){
log.info("WebElement is null..");
return null;
}
boolean status = isDisplayed(element);
if(status){
log.info("element text is .."+element.getText());
return element.getText();
}
else{
return null;
}
}
public String getText(WebElement element){
if(null == element){
log.info("WebElement is null..");
return null;
}
boolean status = isDisplayed(element);
if(status){
log.info("element text is .."+element.getText());
return element.getText();
}
else{
return null;
}
}
}

Just change
private final Logger log = LoggerHelper.getLogger(LoginPage.class);
to
private static final Logger log = LoggerHelper.getLogger(LoginPage.class);

Related

when i am using pojo, i am getting exception?

hi all please check my code
public class Sample1 extends Sample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Balaji-PC\\cucumber\\SamplePro\\driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.facebook.com/");
driver.manage().window().maximize();
Sample s= new Sample1();
WebElement d = s.getUsername();
d.sendKeys("lsmanikandan");
s.getPassword().sendKeys("manikandan");
}
}
Please check below my pojo class
public class Sample {
WebDriver driver;
public Sample() {
PageFactory.initElements(driver, this);
}
#FindBy(id = "email")
private WebElement username;
#FindBy(id = "pass")
private WebElement password;
public WebElement getUsername() {
return username;
}
public WebElement getPassword() {
return password;
}
}
please find below the exception
Exception in thread "main" java.lang.NullPointerException at
org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at
org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy4.sendKeys(Unknown Source) at
org.test.Sample1.main(Sample1.java:18)
The issue in your code is that you are not passing your driver state from child class Sample 1 to based class Sample.
The magic is in these three points
Adding parametrized constructor in Child class - Sample1
public Sample1(WebDriver driver) { super(driver); }
Adding parametrized constructor in Parent Class - Sample
public Sample(WebDriver driver) {
PageFactory.initElements(driver, this);
System.out.println("Page Factory started");
}
Creating object to called page factory in Parent class by passing driver.
Sample s = new Sample1(driver);
public class Sample {
WebDriver driver;
public Sample(WebDriver driver) {
PageFactory.initElements(driver, this);
System.out.println("Page Factory started");
}
#FindBy(id = "email")
private WebElement username;
#FindBy(id = "pass")
private WebElement password;
public WebElement getUsername() {
System.out.println(username.getAttribute("data-testid"));
return username;
}
public WebElement getPassword() {
System.out.println(username.getAttribute("data-testid"));
return password;
} }
public class Sample {
WebDriver driver;
public Sample(WebDriver driver) {
PageFactory.initElements(driver, this);
System.out.println("Page Factory started");
}
#FindBy(id = "email")
private WebElement username;
#FindBy(id = "pass")
private WebElement password;
public WebElement getUsername() {
System.out.println(username.getAttribute("data-testid"));
return username;
}
public WebElement getPassword() {
System.out.println(username.getAttribute("data-testid"));
return password;
} }

Running Selenium Webdriver tests with TestNG in parallel does not sent correct data to browser

I have two TestNG classes with one test method in each. Each test class has its own #Dataprovider. Each test executes functionality on a web application using Selenium Webdriver. The driver is created for each TestNG class via a factory method and threadlocal so driver should be threadsafe. However when running the tests in parallel using testng.xml the same data is being used across both tests causing one to fail. Here is the code. I'm thinking it might be a problem with the thread safety of the Excel Utility class.
/ DriverFactory
#Listeners(ScreenshotListener.class)
public class DriverFactory {
public final static String URL = "http://localhost/Quotation/Development/index.php";
private static List<WebDriverThread> webDriverThreadPool = Collections.synchronizedList(new ArrayList<WebDriverThread>());
private static ThreadLocal<WebDriverThread> driverThread;
#BeforeClass
public static void instantiateDriverObject() {
System.out.println("Before Class");
driverThread = new ThreadLocal<WebDriverThread>() {
#Override
protected WebDriverThread initialValue() {
WebDriverThread webDriverThread = new WebDriverThread();
webDriverThreadPool.add(webDriverThread);
return webDriverThread;}};
}
#BeforeTest
public void setUp() throws Exception {
System.out.println("Before Test");}
public static WebDriver getDriver() throws Exception {
return driverThread.get().getDriver();}
protected String debug(String methodName) throws Exception {
return methodName + " running on Thread " + Thread.currentThread().getId() +
" with instance as " + this + " and driver " + driverThread.get().getDriver().toString();
}
#AfterSuite
public static void closeDriverObjects() {
System.out.println(webDriverThreadPool.size());
for (WebDriverThread webDriverThread : webDriverThreadPool) {
webDriverThread.quitDriver();}
}
}
// WebDriver thread
public class WebDriverThread {
private WebDriver webdriver;
private DriverType selectedDriverType;
private final DriverType defaultDriverType = FIREFOX;
private final String browser = "CHROME"; //System.getProperty("browser").toUpperCase();
private final String operatingSystem = System.getProperty("os.name").toUpperCase();
private final String systemArchitecture = System.getProperty("os.arch");
private final boolean useRemoteWebDriver = Boolean.getBoolean("remoteDriver");
public WebDriver getDriver() throws Exception {
if (null == webdriver) {
selectedDriverType = determineEffectiveDriverType();
DesiredCapabilities desiredCapabilities = selectedDriverType.getDesiredCapabilities();
instantiateWebDriver(desiredCapabilities);}
return webdriver;}
public void quitDriver() {
if (null != webdriver) {
webdriver.quit();
webdriver = null;
}}
private DriverType determineEffectiveDriverType() {
DriverType driverType = defaultDriverType;
try {
driverType = valueOf(browser);}
catch (IllegalArgumentException ignored) {
System.err.println("Unknown driver specified,defaulting to '" + driverType + "'...");}
catch (NullPointerException ignored) {
System.err.println("No driver specified, defaulting to '" + driverType + "'...");}
return driverType;}
private void instantiateWebDriver(DesiredCapabilities desiredCapabilities) throws MalformedURLException {
System.out.println(" ");
System.out.println("Current Operating System: " + operatingSystem);
System.out.println("Current Architecture: " + systemArchitecture);
System.out.println("Current Browser Selection: " + selectedDriverType);
System.out.println(" ");
if (useRemoteWebDriver) {
URL seleniumGridURL = new URL(System.getProperty("gridURL"));
webdriver = new RemoteWebDriver(seleniumGridURL,desiredCapabilities);
}
else
webdriver = selectedDriverType.getWebDriverObject(desiredCapabilities);
}
}
// ValidLoginTest
public class ValidLoginTest extends DriverFactory{
#BeforeMethod
public void setup() throws Exception {
System.err.println(debug("validLoginTest"));
}
//#Test(dataProvider="ValidLogin" ,dependsOnMethods = { "inValidLoginTest" })
#Test(dataProvider="ValidLogin")
public void validLoginTest(String username, String password, String expectedUserName, String expectedUserEmail) throws Exception {
Login login = new Login();
getDriver().get(URL);
String[] loggedin = login.navigateTo()
.enterUserName(username)
.enterPassword(password)
.andSubmit()
.andCheckLoggedIn();
assertEquals(loggedin[0],expectedUserName);
assertEquals(loggedin[1],expectedUserEmail);
}
#AfterMethod
public void teardown() throws Exception {
JavascriptExecutor jsExecutor = (JavascriptExecutor) getDriver();
jsExecutor.executeScript("sessionStorage.clear();");
}
#DataProvider
public Object[][] ValidLogin() throws Exception{
Object[][] testObjArray = ExcelUtils.getTableArray("SystemTestData.xlsx","ValidLogin");
return (testObjArray);}
}
public class InvalidLoginTest extends DriverFactory{
#BeforeMethod
public void setup() throws Exception {
System.err.println(debug("inValidLoginTest"));
}
#Test(dataProvider="InvalidLogin")
public void inValidLoginTest(String username, String password, String expectedResult) throws Exception {
Login login = new Login();
getDriver().get(URL);
String error = login.navigateTo()
.enterUserName(username)
.enterPassword(password)
.andSubmit()
.andCheckValidation();
assertEquals(error, expectedResult);
login.andClose();
}
#DataProvider
public Object[][] InvalidLogin() throws Exception{
Object[][] testObjArray = ExcelUtils.getTableArray("SystemTestData.xlsx","InvalidLogin");
return (testObjArray);}
}
public class Login {
#FindBy(xpath = "/html/body/nav/div/div[2]/ul/li[3]/a")
private WebElement loginMenu;
#FindBy(name = "user")
private WebElement usernameLocator;
#FindBy(name = "password")
private WebElement passwordLocator;
#FindBy(id = "loginUser")
private WebElement loginUserLocator;
#FindBy(css = "#loginForm > div:nth-child(2) > button:nth-child(2)")
private WebElement closeLocator;
#FindBy(id = "loginError")
private WebElement error;
#FindBy(xpath = "/html/body/nav/div/div[2]/ul/li[3]/ul/li[1]/div/div/div/p[1]/strong")
private WebElement loggedInUserName;
#FindBy(xpath = "/html/body/nav/div/div[2]/ul/li[3]/ul/li[1]/div/div/div/p[2]/strong")
private WebElement loggedInUserEmail;
#FindBy(xpath = "/html/body/nav/div/div[2]/ul/li[3]")
private WebElement account;
private WebDriverWait wait;
public Login() throws Exception {
PageFactory.initElements(DriverFactory.getDriver(), this);
wait = new WebDriverWait(DriverFactory.getDriver(), 30);
System.out.println("Login " + DriverFactory.getDriver().toString());
}
public Login navigateTo() throws Exception {
wait.until(ExpectedConditions.visibilityOf(loginMenu));
loginMenu.click();
return this;
}
public Login enterUserName(String username) {
wait.until(ExpectedConditions.visibilityOf(usernameLocator));
usernameLocator.clear();
for(int i = 0; i < username.length(); i++){
char c = username.charAt(i);
String s = new StringBuilder().append(c).toString();
usernameLocator.sendKeys(s);
}
return this;
}
public Login enterPassword(String password) {
wait.until(ExpectedConditions.visibilityOf(passwordLocator));
passwordLocator.clear();
passwordLocator.sendKeys(password);
return this;
}
public Login andSubmit() {
wait.until(ExpectedConditions.visibilityOf(loginUserLocator));
loginUserLocator.click();
return this;
}
public String[] andCheckLoggedIn() {
String[] actualResult = new String[2];
wait.until(ExpectedConditions.visibilityOf(account));
account.click();
wait.until(ExpectedConditions.visibilityOf(loggedInUserName));
actualResult[0] = loggedInUserName.getText();
actualResult[1] = loggedInUserEmail.getText();
return actualResult;
}
public String andCheckValidation() {
wait.until(ExpectedConditions.visibilityOfAllElements(error));
return error.getText();
}
public void andClose() throws Exception {
wait.until(ExpectedConditions.visibilityOf(closeLocator));
closeLocator.click();
}
}
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
public static Object[][] getTableArray(String FilePath, String SheetName) throws Exception {
String[][] tabArray = null;
try {
FileInputStream ExcelFile = new FileInputStream(FilePath);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int startRow = 1;
int startCol = 1;
int totalRows = ExcelWSheet.getLastRowNum();
int totalCols = ExcelWSheet.getRow(0).getLastCellNum();
tabArray = new String[totalRows][totalCols -startCol];
for (int row = startRow; row <= totalRows; row++) {
for (int col = startCol; col < totalCols; col++){
tabArray[row - startRow][col - startCol] = getCellData(row, col);
}}}
catch (FileNotFoundException e){
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
}
catch (IOException e){
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
}
return(tabArray);
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try{
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
if (Cell == null || Cell.getCellTypeEnum() == CellType.BLANK) {
return "";
}else{
String CellData = Cell.getStringCellValue();
return CellData;
}}catch (Exception e){
System.out.println(e.getMessage());
throw (e);
}}}
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Quotation" parallel="classes" thread-count="3" verbose="1" >
<test name="System Test" >
<classes>
<class name="com.quotation.systemtest.tests.ValidLoginTest"/>
<class name="com.quotation.systemtest.tests.InvalidLoginTest"/>
</classes>
</test>
</suite>
[Testng_Result][1]
[1]: https://i.stack.imgur.com/vLx0y.png

How to Set up POM Structure using selenium java and (TestNG Framework)

I'm new for QA automation and I have average knowledge in java,
so I decided to use (Selenium+Java) to do automation.
I will attach the code I did to the automation.and the script runs smoothly.
But the Structure I did is incorrect as I want to follow the (POM-Selenium).POM-Page Oriented Model
This Script navigates as Follows
Login(Page)-->Peronal(Drop/down Selection)--->AddEdit((Drop/down Selection))-->Personal(Page)-->Add(Button)-->PersonalDetails(Page)
The test scenario is......
the user should "login" to the system, and have to click "personal" drop down in the navigation tab then there will be an "AddEdit" drop downselection.then the user is directed to the page titled as "personal", the user should click "Add" button on that page to get directed to another page called "personal Details" user can add the relevant fields which are provided from the page to add a new Client.
Please help me to arrange this to POM Structure.because I'm having very hard time to think how it goes.what frustrates me is in order user to add a relevant record he/she should be logged in to the system and in POM it says login is a separate page I have to navigate through three pages to complete the task.it would be great if you can help me out.and it's open to discussion and sorry if my English is bad. and please consider me as a total noob when it comes to automation :) thanks!
This is the Test Script I wrote...
package TestNG;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import org.openqa.selenium.*;
import org.openqa.selenium.By.ByXPath;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.*;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
//public String baseUrl;
//public String driverPath;
//public WebDriver driver;
public class Tester {
public String baseUrl = "http://xxx.xxx.xxx.xxx:xxxx/xxx/";
public String driverPath = "C:\\Users\\User\\Desktop\\geckodriver.exe";
public WebDriver driver;
#Test(priority = 0)
public void Login() {
System.out.println("launching firefox browser");
System.setProperty("webdriver.gecko.driver", driverPath);
driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement username = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id=\"userId\"]")));
username.sendKeys("xxxxxxxxx");
WebElement password = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id=\"loginPassword\"]")));
password.sendKeys("xxxxxxxxxxxxxxxxxx");
WebElement button = (new WebDriverWait(driver, 10)).until(ExpectedConditions
.presenceOfElementLocated(By.xpath("/html/body/div/div[3]/div/div/form/div[3]/div[2]/div/button")));
button.click();
String expectedTitle = "xxxxxxxxxxxxxxxxxxxxxxxx";
String actualTitle = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div[2]/div[2]/div/div/h1")))
.getText().toString();
// System.out.println(actualTitle);
Assert.assertEquals(actualTitle, expectedTitle);
// driver.close();
}
#Test(priority = 1)
public void Personal_Tab_Selection() {
clickWhenReady("/html/body/div[2]/div[2]/nav/div/div[2]/div/div[1]/ul/li[5]/a", 10, driver);
}
#Test(priority = 2)
public void Add_Edit_Selection() {
clickLinkByHref("/rsa/5/15/staff/n/i/list", driver);
}
#Test(priority = 3)
public void Add_Button() {
clickWhenReady("/html/body/div[2]/div[2]/div/div[2]/form/div[2]/div/div/a", 10, driver);
}
#Test(priority = 4)
public void Radio_Button_AMW() {
WebElement amw_radio = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[1]/div/div/label[1]")));
amw_radio.click();
}
#Test(priority = 5)
public void Radio_Button_service_provider() {
WebElement service_provider = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[2]/div/div/label[1]")));
service_provider.click();
}
#Test(priority = 6)
public void Service_Provider_Name_select() {
WebElement Service_Provider_DD = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[3]/div/div/a")));
Service_Provider_DD.click();
driver.findElement(By.cssSelector("ul > li:nth-child(2)")).click();
}
#Test(priority = 7)
public void Employee_Code_Enter() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[5]/div/input"))
.sendKeys("01112");
}
#Test(priority = 8)
public void Click_Salutation() {
WebElement Salutation_DD = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[6]/div/div/a")));
Salutation_DD.click();
}
#Test(priority = 9)
public void Salutation_Click() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[6]/div/div/div/ul/li[5]"))
.click();
}
#Test(priority = 10)
public void employee_name() {
WebElement empname = driver
.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[7]/div/input"));
empname.sendKeys("Test2");
}
#Test(priority = 11)
public void Sap_plant_code() {
WebElement plant_code = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[8]/div/div/a")));
plant_code.click();
}
#Test(priority = 12)
public void sap_code_set() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[8]/div/div/div/ul/li[3]"))
.click();
}
#Test(priority = 13)
public void sap_vendor_code() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[9]/div/input"))
.sendKeys("test_2");
}
#Test(priority = 14)
public void employee_role_select() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[10]/div/div/ul")).click();
}
#Test(priority = 15)
public void select_Technician_role() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[10]/div/div/div/ul/li"))
.click();
}
#Test(priority = 16)
public void select_status() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[11]/div/div/a")).click();
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[11]/div/div/div/ul/li[1]"))
.click();
}
#Test(priority = 17)
public void click_save_button() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[2]/div/div/button[1]")).click();
}
#Test(priority = 18)
public void Record_add_notification_Check() {
if ((new WebDriverWait(driver, 10)).until(ExpectedConditions
.presenceOfElementLocated(By.xpath("/html/body/div[2]/div[3]/div/div/button"))) != null) {
driver.findElement(By.xpath("/html/body/div[2]/div[3]/div/div/button")).click();
} else {
infoBox("not Added", "Not Added");
}
}
public static void infoBox(String infoMessage, String titleBar) {
JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
public static void clickWhenReady(String location, int timeout, WebDriver driver) {
WebElement element = null;
WebDriverWait wait = new WebDriverWait(driver, timeout);
element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(location)));
element.click();
}
public static void clickLinkByHref(String href, WebDriver driver) {
List<WebElement> anchors = driver.findElements(By.tagName("a"));
Iterator<WebElement> i = anchors.iterator();
while (i.hasNext()) {
WebElement anchor = i.next();
if (anchor.getAttribute("href").contains(href)) {
anchor.click();
break;
}
}
}
}
A few words about your script:
presenceOfElementLocated(By.xpath("//*[#id=\"userId\"]")) - If an element have an id you should always try to use id instead of xpath
By.xpath("/html/body/div/div[3]/div/div/form/div[3]/div[2]/div/button")) - It is recommended to use logical xpath instead of absolute xpath as much as possible. Else your xpath becomes vulnerable.
Now as you are willing to follow the POM, you need to define all the elements of a page in a single page which will be called the PageFactory. Likewise, all the Elements of a webpage will reside in separate class.
For e.g. an entry for an element on a webpage may look like:
#FindBy(id="user_login")
WebElement username;
As you are using TestNG, you can move the Browser related code to a seperate class Browserfactory. From your test class, within #BeforeTest Annotation call the methods of Browserfactory to initialize the browser, open the url.
These are some of the basic steps to implement your code through POM.
Let me know if this solves your query.
These are the classes I created depending on the pages of UI,ill attach the structure as a snapshot too :)
public class Driver_class {
private static String baseUrl;
private static String driverPath;
public static WebDriver driver;
public static WebDriver getDriver() {
baseUrl = "http://xxx.xxx.xxx.xxx:xx:xx\\Desktop\\geckodriver.exe";
if (driver == null) {
System.setProperty("webdriver.gecko.driver", "C:\\Users\\User\\Desktop\\geckodriver.exe");
driver = new FirefoxDriver();
driver.get(baseUrl);
}
return driver;
}
}
public class Login {
public WebElement uid;
public WebElement pwd;
public WebElement loginbtn;
public void get_elements(WebDriver driver) {
uid = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id=\"userId\"]")));
pwd = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id=\"loginPassword\"]")));
loginbtn = (new WebDriverWait(driver, 10)).until(ExpectedConditions
.presenceOfElementLocated(By.xpath("/html/body/div/div[3]/div/div/form/div[3]/div[2]/div/button")));
}
public void customerLogin() {
this.uid.sendKeys("xxxxxxxx");
this.pwd.sendKeys("xxxxxxxxxxx");
this.loginbtn.click();
}
}
public class Navigation {
public WebElement Personal_Tab;
public WebElement Add_Edit_p;
public void navigate_personal_button(WebDriver driver) {
clickWhenReady("/html/body/div[2]/div[2]/nav/div/div[2]/div/div[1]/ul/li[5]/a", 10, driver);
}
public void navigate_personal_add_button(WebDriver driver) {
clickLinkByHref("/rsa/5/15/staff/n/i/list", driver);
}
public static void clickWhenReady(String location, int timeout, WebDriver driver) {
WebElement element = null;
WebDriverWait wait = new WebDriverWait(driver, timeout);
element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(location)));
element.click();
}
public void clickLinkByHref(String href, WebDriver driver) {
List<WebElement> anchors = driver.findElements(By.tagName("a"));
Iterator<WebElement> i = anchors.iterator();
while (i.hasNext()) {
WebElement anchor = i.next();
if (anchor.getAttribute("href").contains(href)) {
anchor.click();
break;
}
}
}
}
public class Personal_Details {
WebElement amw_radio;
WebElement service_provider;
WebElement Service_Provider_DD;
//WebElement Employee_Code_Enter;
WebElement Click_Salutation;
WebElement Salutation_DD;
WebElement empname;
WebElement plant_code;
//WebElement
public void Radio_Button_AMW(WebDriver driver) {
amw_radio = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[1]/div/div/label[1]")));
amw_radio.click();
}
public void Radio_Button_service_provider(WebDriver driver) {
service_provider = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[2]/div/div/label[1]")));
service_provider.click();
}
public void Service_Provider_Name_select(WebDriver driver) {
Service_Provider_DD = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[3]/div/div/a")));
Service_Provider_DD.click();
driver.findElement(By.cssSelector("ul > li:nth-child(2)")).click();
}
public void Employee_Code_Enter(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[5]/div/input"))
.sendKeys("01112");
}
public void Click_Salutation(WebDriver driver) {
Salutation_DD = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[6]/div/div/a")));
Salutation_DD.click();
}
public void Salutation_Click(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[6]/div/div/div/ul/li[5]"))
.click();
}
public void employee_name(WebDriver driver) {
empname = driver
.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[7]/div/input"));
empname.sendKeys("Test2");
}
public void Sap_plant_code(WebDriver driver) {
plant_code = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[8]/div/div/a")));
plant_code.click();
}
public void sap_code_set(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[8]/div/div/div/ul/li[3]"))
.click();
}
public void sap_vendor_code(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[9]/div/input"))
.sendKeys("test_2");
}
public void employee_role_select(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[10]/div/div/ul")).click();
}
public void select_Technician_role(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[10]/div/div/div/ul/li"))
.click();
}
public void select_status(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[11]/div/div/a")).click();
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[11]/div/div/div/ul/li[1]"))
.click();
}
public void click_save_button(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[2]/div/div/button[1]")).click();
}
public void Record_add_notification_Check(WebDriver driver) {
if ((new WebDriverWait(driver, 10)).until(ExpectedConditions
.presenceOfElementLocated(By.xpath("/html/body/div[2]/div[3]/div/div/button"))) != null) {
driver.findElement(By.xpath("/html/body/div[2]/div[3]/div/div/button")).click();
} else {
infoBox("not Added", "Not Added");
}
}
public static void infoBox(String infoMessage, String titleBar) {
JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
}
public class Personal_list {
WebElement add_btn;
public void find_add_btn(WebDriver driver) {
String add_btn_path = "/html/body/div[2]/div[2]/div/div[2]/form/div[2]/div/div/a";
detect_element_click(driver, add_btn_path);
}
public void detect_element_click(WebDriver webDriver, String xp) {
WebDriverWait wait = new WebDriverWait(webDriver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xp))).click();
}
}
This is the TestCaseClass Which executes all test_cases
public class TestCases {
public WebDriver driver = Driver_class.getDriver();
#Test(priority = 0)
public void newCustomerLogin() {
Login rsaLogin = PageFactory.initElements(driver, Login.class);
rsaLogin.get_elements(driver);
rsaLogin.customerLogin();
}
#Test(priority = 1)
public void click_Personal_tab() {
Navigation n = PageFactory.initElements(driver, Navigation.class);
n.navigate_personal_button(driver);
n.navigate_personal_add_button(driver);
}
#Test(priority=2)
public void click_add_tab() {
Personal_list ps= PageFactory.initElements(driver,Personal_list.class);
ps.find_add_btn(driver);
}
#Test(priority=3)
public void Enter_personal_details(){
Personal_Details d= new Personal_Details();
d.Radio_Button_AMW(driver);
d.Radio_Button_service_provider(driver);
d.Service_Provider_Name_select(driver);
d.Employee_Code_Enter(driver);
d.Click_Salutation(driver);
d.Salutation_Click(driver);
d.employee_name(driver);
d.Sap_plant_code(driver);
d.sap_code_set(driver);
d.sap_vendor_code(driver);
d.employee_role_select(driver);
d.select_Technician_role(driver);
d.select_status(driver);
d.click_save_button(driver);
d.Record_add_notification_Check(driver);
}
}

Configuring ExtentReports to provide accurate test statuses and screenshot on failure

I am having some difficulty tweaking ExtentReports to provide the desired output.
I have a simple test framework with TestNG, using a TestBase class to do the heavy lifting to keep tests simple. I wish to implement ExtentReports in a simple fashion, using the TestNG ITestResult interface to report Pass, Fail and Unknown.
Here are example tests, 1 pass and 1 deliberate fail:
public class BBCTest extends TestBase{
#Test
public void bbcHomepagePass() throws MalformedURLException {
assertThat(driver.getTitle(), (equalTo("BBC - Home")));
}
#Test
public void bbcHomePageFail() throws MalformedURLException {
assertThat(driver.getTitle(), (equalTo("BBC - Fail")));
}
And here is the relevant section in TestBase:
public class TestBase implements Config {
protected WebDriver driver = null;
private Logger APPLICATION_LOGS = LoggerFactory.getLogger(getClass());
private static ExtentReports extent;
private static ExtentTest test;
private static ITestContext context;
private static String webSessionId;
#BeforeSuite
#Parameters({"env", "browser"})
public void beforeSuite(String env, String browser) {
String f = System.getProperty("user.dir") + "\\test-output\\FabrixExtentReport.html";
ExtentHtmlReporter h = new ExtentHtmlReporter(f);
extent = new ExtentReports();
extent.attachReporter(h);
extent.setSystemInfo("browser: ", browser);
extent.setSystemInfo("env: ", env);
}
#BeforeClass
#Parameters({"env", "browser", "login", "mode"})
public void initialiseTests(String env, String browser, String login, String mode) throws MalformedURLException {
EnvironmentConfiguration.populate(env);
WebDriverConfigBean webDriverConfig = aWebDriverConfig()
.withBrowser(browser)
.withDeploymentEnvironment(env)
.withSeleniumMode(mode);
driver = WebDriverManager.openBrowser(webDriverConfig, getClass());
String baseURL = EnvironmentConfiguration.getBaseURL();
String loginURL = EnvironmentConfiguration.getLoginURL();
APPLICATION_LOGS.debug("Will use baseURL " + baseURL);
switch (login) {
case "true":
visit(baseURL + loginURL);
break;
default:
visit(baseURL);
break;
}
driver.manage().deleteAllCookies();
}
#BeforeMethod
public final void beforeTests(Method method) throws InterruptedException {
test = extent.createTest(method.getName());
try {
waitForPageToLoad();
webSessionId = getWebSessionId();
} catch (NullPointerException e) {
APPLICATION_LOGS.error("could not get SessionID");
}
}
#AfterMethod
public void runAfterTest(ITestResult result) throws IOException {
switch (result.getStatus()) {
case ITestResult.FAILURE:
test.fail(result.getThrowable());
test.fail("Screenshot below: " + test.addScreenCaptureFromPath(takeScreenShot(result.getMethod().getMethodName())));
test.fail("WebSessionId: " + webSessionId);
break;
case ITestResult.SKIP:
test.skip(result.getThrowable());
break;
case ITestResult.SUCCESS:
test.pass("Passed");
break;
default:
break;
}
}
private String takeScreenShot(String methodName) {
String path = System.getProperty("user.dir") + "\\test-output\\" + methodName + ".jpg";
try {
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File(path));
} catch (Exception e) {
APPLICATION_LOGS.error("Could not write screenshot" + e);
}
return path;
}
#AfterClass
public void tearDown() {
driver.quit();
}
#AfterSuite()
public void afterSuite() {
extent.flush();
}
Here is the report:
The issues are:
The name of the failed test is not recorded at left hand menu
The screenshot is not displayed despite correctly being taken
It is reporting both a Pass and Unexpected for the passed test
Version 3.0
Most of code is provided by person created this library, i just modified to your needs.
public class TestBase {
private static ExtentReports extent;
private static ExtentTest test;
#BeforeSuite
public void runBeforeEverything() {
String f = System.getProperty("user.dir")+ "/test-output/MyExtentReport.html";
ExtentHtmlReporter h = new ExtentHtmlReporter(f);
extent = new ExtentReports();
extent.attachReporter(h);
}
#BeforeMethod
public void runBeforeTest(Method method) {
test = extent.createTest(method.getName());
}
#AfterMethod
public void runAfterTest(ITestResult result) {
switch (result.getStatus()) {
case ITestResult.FAILURE:
test.fail(result.getThrowable());
test.fail("Screenshot below: " + test.addScreenCaptureFromPath(takeScreenShot(result.getMethod().getMethodName())));
break;
case ITestResult.SKIP:
test.skip(result.getThrowable());
break;
case ITestResult.SUCCESS:
test.pass("Passed");
break;
default:
break;
}
extent.flush();
}
protected String takeScreenShot(String methodName) {
String path = "./screenshots/" + methodName + ".png";
try {
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File(path));
} catch (Exception e) {
APPLICATION_LOGS.error("Could not write screenshot" + e);
}
return path;
}
}
You need several changes to make. Instantiate the ExtentReport & add configuration information in any of the configuration methods except BeforeClass.
#BeforeTest
#Parameters({"env", "browser"})
public void initialiseTests(String env, String browser, String emulatorMode, String mode) {
EnvironmentConfiguration.populate(env);
WebDriverConfigBean webDriverConfig = aWebDriverConfig()
.withBrowser(browser)
.withDeploymentEnvironment(env)
.withSeleniumMode(mode);
driver = WebDriverManager.openBrowser(webDriverConfig, getClass());
APPLICATION_LOGS.debug("Will use baseURL " + EnvironmentConfiguration.getBaseURL());
try {
visit(EnvironmentConfiguration.getBaseURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
driver.manage().deleteAllCookies();
}
Initailize test = extent.startTest(testName); in the #BeforeMethod section.
#BeforeMethod
public void beforeM(Method m) {
test = extent.startTest(m.getName());
}
And, you may call extent.endTest(test); in the #AfterTest method.
#AfterTest
public void afterTests() {
extent.endTest(test);
extent.close();
}
}
And, to log your step info call test.log(LogStatus, "your info to show"); with appropirate status.

How can I call the Weblement to the other class

public class LoginPagePages {
#FindBy(how=How.XPATH,using="//div[#class='validation-summary-errors text-danger']/ul/li")
WebElement incorrect_username;
}
How can I pass the WebElement incorrect_username; to the class LoginPageTestCase, so that I can get its text into String errorsign and use it for my Assertion
public class LoginPageTestCase {
#Test(priority=1)
public void IncorrectPassword() {
String errorsign = I NEED TO CALL HERE THE "WebElement incorrect_username".getText();
Assert.assertEquals(errorsign, "Username is incorrect");
Add_Log.info("Login Failed");
}
You can create an instance of LoginPagePages in your test and use getter to get it
public class LoginPagePages {
#FindBy(how=How.XPATH,using="//div[#class='validation-summary-errors text-danger']/ul/li")
private WebElement incorrect_username;
public WebElement getIncorrectUsername {
return incorrect_username;
}
}
public class LoginPageTestCase {
#Test(priority=1)
public void IncorrectPassword() {
LoginPagePages loginPage = new LoginPagePages();
String errorsign = loginPage.getIncorrectUsername().getText();
Assert.assertEquals(errorsign, "Username is incorrect");
Add_Log.info("Login Failed");
}
}