#Test method is not waiting selenium code to complete its execution - java

package demoActitime;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class LoginActitime {
private String UN;
private String Pass;
private WebElement username;
private WebElement password;
private WebDriver driver = new FirefoxDriver();
private String Url = "http://demo.actitime.com/";
private String Urlvalid = "http://demo.actitime.com/user/submit_tt.do";
private String expected = null;
private String actual = null;
private String xpathUsername = null;
private String xpathPassword = null;
private String xpathLogin = null;
#BeforeMethod
public void findElements()
{
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get(Url);
xpathUsername = "//input[#id='username']";
xpathPassword = "//input[#type='password']";
xpathLogin = "//a[#id='loginButton']/div";
}
#AfterMethod
public void doTask()
{
System.out.println(expected);
driver.findElement(By.xpath(xpathUsername)).clear();
driver.findElement(By.xpath(xpathPassword)).clear();
driver.findElement(By.xpath(xpathUsername)).sendKeys(UN);
driver.findElement(By.xpath(xpathPassword)).sendKeys(Pass);
driver.findElement(By.xpath(xpathLogin)).click();
actual = driver.getTitle();
Assert.assertEquals(actual, expected);
// driver.quit();
}
#Test(priority = 0)
public void LoginValidUNInvalidPass()
{
this.UN="admin";
this.Pass="basheer";
System.out.println("LoginValidUNInvalidPass");
expected = "actiTIME - Login";
}
#Test()
public void LoginValidUNValidPass()
{
this.UN="admin";
this.Pass="manager";
System.out.println("LoginValidUNValidPass");
expected = "actiTIME - Enter Time-Track";
}
#Test
public void LoginInValidUNInvalidPass()
{
this.UN="basheer";
this.Pass="basheer";
System.out.println("LoginInValidUNInvalidPass");
expected = "actiTIME - Login";
}
#Test
public void LoginInValidUNValidPass()
{
this.UN="basheer";
this.Pass="manager";
System.out.println("LoginInValidUNValidPass");
expected = "actiTIME - Login";
}
}
This is my Updated Code. I have removed the initialization, finding of elements in aftermethod and placed in beforemethod. When i pass valid username and password, #After Method is not waiting for web driver to login, its showing test execution is completed.

Try below sample program, it might helps you. I had restructured your code and used #BeforeTest & #AfterTest. Let me know it is working for you or not.
package demoActitime;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class LoginActitime {
//defining all required variables
private String UN = "";
private String Pass = "";
private WebElement username = null;
private WebElement password = null;
private WebElement login = null;
private WebDriver driver = null;
private String Url = "http://demo.actitime.com/";
private String Urlvalid = "http://demo.actitime.com/user/submit_tt.do";
private String expected = null;
private String actual = null;
private String xpathUsername = null;
private String xpathPassword = null;
private String xpathLogin = null;
#BeforeTest
public void findElements()
{
//initialising webdriver with url
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get(Url);
//initialising webelements
xpathUsername = "//input[#id='username']";
xpathPassword = "//input[#type='password']";
xpathLogin = "//a[#id='loginButton']/div";
username = driver.findElement(By.xpath(xpathUsername));
password = driver.findElement(By.xpath(xpathPassword));
login = driver.findElement(By.xpath(xpathLogin));
}
#AfterTest
public void doTask()
{
System.out.println(expected);
username.clear();
password.clear();
}
#Test(priority = 0)
public void invalidLogin()
{
this.UN="validUser";
this.Pass="invalidPassword";
username.sendKeys(UN);
password.sendKeys(Pass);
login.click();
expected = "expected title";
actual = driver.getTitle();
Assert.assertEquals(actual, expected);
}
#Test(priority = 1)
public void validLogin()
{
this.UN="validUser";
this.Pass="validPassword";
username.sendKeys(UN);
password.sendKeys(Pass);
login.click();
expected = "expected title";
actual = driver.getTitle();
Assert.assertEquals(actual, expected);
}
}

After clicking login button, its taking time for webpage to change its title. Hence your getting feeling that #afterMethod is not waiting to complete login action.
In case of invalid credentials, after clicking on login button, the webpage title is not changing, and your getting feeling that #after Method is not waiting for login to happen.
Put some 2 seconds wait after clicking on login button and your script will work as expected:
driver.findElement(By.xpath(xpathLogin)).click();
Thread.sleep(2000);

Related

How do I click on this autoComplete countryName?

This is the link I wanted to automate. But I am not being able to click on countryName. I wanted to enter "na" in the searchField and then click on "Nepal" using the list attribute i.e list.get(i).click() but I have not been able to. Please help
package autoComplete;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class AutoCompleteCountry {
WebDriver driver;
String url = "https://practice-cybertekschool.herokuapp.com/autocomplete";
By countryField = By.id("myCountry");
By countryList = By.xpath("//input[#type='hidden']");
#BeforeTest
public void getUrl() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
driver.get(url);
}
#Test
public void autoCompleteTest() throws InterruptedException {
driver.findElement(countryField).sendKeys("N");
List<WebElement> listOfCountry = driver.findElements(countryList);
// driver.findElement(nepalClick).click();
for (int i = 0; i < listOfCountry.size(); i++) {
// System.out.println(list);
String searchText = listOfCountry.get(i).getAttribute("value");
System.out.println(searchText);
if (searchText.equals("Nepal")) {
listOfCountry.get(i).click();
}
}
}
#AfterTest
public void tearDown() throws InterruptedException {
Thread.sleep(5000);
driver.quit();
}
}
This is the error screenshot:
Error Screenshot
You needn't iterate through the whole list if you just want to click the "Nepal" option. Does the following help at all?
driver.findElement(By.CSS_SELECTOR, 'input[value="Nepal"]').click()
you can use Webdriver wait with a customExpected Condition like this below
Instead of using implicit wait use WebDriverwait for Fluentwait
private static ExpectedCondition<Boolean> waitForDropdownElement(By by, String value) {
return ( driver -> {
List<WebElement> listOfCountry = driver.findElements(by);
for (int i = 0; i < listOfCountry.size(); i++) {
String searchText = listOfCountry.get(i).getText();
if (searchText.equals(value)) {
listOfCountry.get(i).click();
return true;
}
}
return false;
});
}
Also modified below locator like this, as you will get element not clickable exception on using that
By countryList = By.xpath("//div[#id='myCountryautocomplete-list']//div");
Full code below which is working for me
import io.github.bonigarcia.wdm.WebDriverManager;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class AutoCompleteCountry {
WebDriver driver;
String url = "https://practice-cybertekschool.herokuapp.com/autocomplete";
By countryField = By.id("myCountry");
By countryList = By.xpath("//div[#id='myCountryautocomplete-list']//div");
#BeforeTest
public void getUrl() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
driver.get(url);
}
#Test
public void autoCompleteTest() throws InterruptedException {
driver.findElement(countryField).sendKeys("N");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(60));
wait.until(waitForDropdownElement(countryList, "Nepal"));
}
#AfterTest
public void tearDown() throws InterruptedException {
Thread.sleep(5000);
driver.quit();
}
private static ExpectedCondition<Boolean> waitForDropdownElement(By by, String value) {
return (driver -> {
List<WebElement> listOfCountry = driver.findElements(by);
for (int i = 0; i < listOfCountry.size(); i++) {
String searchText = listOfCountry.get(i).getText();
if (searchText.equals(value)) {
listOfCountry.get(i).click();
return true;
}
}
return false;
});
}
}

Browser is not launching for the second TestNG Test case

The browser is not launching for the second testcase of a TestNG Test group.
Tried playing with the Before and AfterTest but still the browser is not launching. also add checks the browser running. not sure what I miss here.
Error:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#Email"}
(Session info: chrome=91.0.4472.77)
this causes the b browser is not launched at the time
Driver Class:
package com.portalHelpers;
import org.openqa.selenium.Alert;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.util.Date;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.service.DriverService;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import static java.lang.String.valueOf;
public class WebDriverHelper extends EventFiringWebDriver {
public static RemoteWebDriver remoteDriver;
protected static HtmlUnitDriver htmlDriver;
protected static Alert _alert;
protected static DriverService cds;
private static String driverClass = System.getProperty("driverClass");
public static long now = new Date().getTime();
public static com.itextpdf.text.Document dataFeed;
public final static String DefaultTimeOut = "40000";
public final static int TimeOut = 90;
protected static String chrome_driver_location = "/Users/me/Downloads/chromedriver";
public static String url = System.getProperty("url");
public static String browser = System.getProperty("browser");
private static String platform = Platform.getCurrent().name();
private static String CHROME_DRIVER = "chrome_driver";
//******************URLs************************************************************//
public static String url_test = "www.google.com";
public static String url_live = "www.google.com";
//******************Browser settings************************************************************//
//Browser settings
static {
//
if (browser.equalsIgnoreCase("chrome")) {
if (platform.equalsIgnoreCase("Mac")) {
CHROME_DRIVER = CHROME_DRIVER + "_mac";
} else if (platform.equalsIgnoreCase("LINUX")) {
CHROME_DRIVER = CHROME_DRIVER + "_linux";
} else {
CHROME_DRIVER = CHROME_DRIVER + "_win.exe";
}
setWebDriverToChrome();
}
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
remoteDriver.close();
}
});
}
static {
if (url.equalsIgnoreCase("url_test")) {
open_test();
} else if (url.equalsIgnoreCase("url_live")) {
open_live();
}
}
public WebDriverHelper() {
super(remoteDriver);
manage().window().maximize();
manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
#BeforeTest
public void setUp () throws Exception{
setWebDriverToChrome();}
#AfterTest
public void tearDown () throws Exception{
if(remoteDriver !=null){
remoteDriver.close();
}}
public static void setWebDriverToChrome () {
System.setProperty("webdriver.chrome.driver",chrome_driver_location);
cds = new ChromeDriverService.Builder()
.usingDriverExecutable(new File(chrome_driver_location))
.usingAnyFreePort()
.build();
try {
cds.start();
} catch (IOException e) {
throw new IllegalStateException(e.getMessage());
}
ChromeOptions opt = new ChromeOptions();
opt.addArguments("disable-infobars");
opt.addArguments("--start-maximized");
opt.addArguments("--disable-extensions");
remoteDriver = new RemoteWebDriver(cds.getUrl(), opt);
}
public void openWebPage (String url){
//Get url and maximize the window
remoteDriver.get(url);
remoteDriver.manage().window().maximize();
}
public static void open_test () {
remoteDriver.get(url_test);
remoteDriver.manage().window().maximize();
}
public static void open_live() {
remoteDriver.get(url_live);
// remoteDriver.manage().window().maximize();
}
public static WebDriver getSelenium () {
if ((remoteDriver == null) && (!"noBrowser".equals(driverClass))) {
throw new IllegalStateException("Selenium client is not initialised.");
}
return remoteDriver;
}
}
Test Class:
package Testsuites;
import com.portalHelpers.PageObjects;
import com.portalHelpers.WebDriverHelper;
import com.portalHelpers.SeleniumMethodsHelper;
import org.testng.Assert;
import org.testng.annotations.Test;
public class testSuite extends WebDriverHelper {
PageObjects pageObjects = new PageObjects();
SeleniumMethodsHelper seleniumMethodsHelper = new SeleniumMethodsHelper();
String user1 = "user1t#google.com";
String standardPass = "1234";
String user2 = "user2#gmail.com";
#Test(groups = "MainFlowTests")
public void preparation(){
String actual_url = getCurrentUrl();
System.out.println(actual_url);
//sending the username and password parameters to the login method//
PageObjects.login_logic(remoteDriver,user1, standardPass);
//Asserting the user logged in is the one we used and that we are on logged in//
String name = PageObjects.account_Email().getText();
System.out.println(name);
Assert.assertEquals(name,useer1);
seleniumMethodsHelper.sleep(3);
SeleniumMethodsHelper.mouseOver(PageObjects.promo_Button());
seleniumMethodsHelper.sleep(8);
}
#Test(groups = "MainFlowTests")
public void offerCreation(){
String actual_url = getCurrentUrl();
System.out.println(actual_url);
//sending the username and password parameters to the login method//
//PageObjects.email_Field().click();
PageObjects.login_logic(remoteDriver,dryFoodsCam, standardPass);
seleniumMethodsHelper.sleep(3);
}
}
Image shows the TestNG configuration.
Hope you can find what I miss here or if something is wrong.
Thanks

How to use REST API mark tests as fail?

I use this https://www.browserstack.com/docs/automate/selenium/view-test-results/mark-tests-as-pass-fail as reference.
But I not able to let the REST API shows 'fail'. May I know what is my problem? I also attached the text logs, it shows 'Run JavaScript......'
, is it correct?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.JavascriptExecutor;
public class test1 {
public WebDriver driver = null;
public static final String USERNAME = "";
public static final String AUTOMATE_KEY = "";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "#hub-cloud.browserstack.com/wd/hub";
#BeforeClass
public void setup() throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("os", "Windows");
caps.setCapability("os_version", "10");
caps.setCapability("browser", "Chrome");
caps.setCapability("browser_version", "80");
caps.setCapability("name", "Test1");
driver = new RemoteWebDriver(new URL(URL), caps);
}
#Test (priority = 1)
public void test_1() {
driver.get("https://youtube.com");
String actualUrl = "https://www.youtube.com/";
String expectedUrl = "https://www.youtube.com/";
Assert.assertEquals(actualUrl, expectedUrl);
JavascriptExecutor jse = (JavascriptExecutor)driver;
if (actualUrl.equals(expectedUrl)) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"Url matched!\"}}");
}
else {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"Url not matched\"}}");
}
}
#Test (priority = 2)
public void test_2() {
driver.get("https://google.com");
String actualUrl = "https://www.google.com/";
String expectedUrl = "https://www.youtube1.com/";
Assert.assertEquals(actualUrl, expectedUrl);
JavascriptExecutor jse = (JavascriptExecutor)driver;
if (actualUrl.equals(expectedUrl)) {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \"passed\", \"reason\": \"Url matched!\"}}");
}
else {
jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\"failed\", \"reason\": \"Url not matched\"}}");
}
}
#AfterClass
public void tearDown() {
driver.quit();
}
}
I tested with youtube and google url.
Assert.assertEquals(actualUrl, expectedUrl);
is not a soft assert , it will stop the command execution so the test won't reach the api line.
remove that from your tests or use soft assert .
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(actualUrl, expectedUrl)

Can you tell me where i did mistake

package hrmInfoModule;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test;
public class Hrmlogin {
public WebDriver driver;
#BeforeTest
public void openbrowser()
{
System.setProperty("webdriver.chrome.driver", "D:\\Software\\chromedriver.exe");
driver = new ChromeDriver ();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
#Test
public void login() throws InterruptedException
{
String Url="https://opensource-demo.orangehrmlive.com/";
String ID ="Admin";
String Pswrd="admin123";
driver.get(Url);
WebElement login = driver.findElement(By.id("txtUsername"));
login.sendKeys(ID);
WebElement paswrd = driver.findElement(By.id("txtPassword"));
paswrd.sendKeys(Pswrd);
WebElement btn = driver.findElement(By.id("btnLogin"));
btn.click();
Thread.sleep(2000);
}
#Test
public WebElement Admin() throws InterruptedException
{
Thread.sleep(2000);
WebElement Admin = driver.findElement(By.xpath(("//*[#id='menu_admin_viewAdminModule']")));
return Admin;
}
#Test
public WebElement JobTitle(WebElement Admin) throws InterruptedException
{
Thread.sleep(2000);
WebElement job = driver.findElement(By.xpath("//*[#id='menu_admin_viewAdminModule']//following-sibling::ul/li[2]/a"));
WebElement jobtitles = driver.findElement(By.xpath("//*[#id='menu_admin_viewAdminModule']//following-sibling::ul/li[2]/ul/li[1]/a"));
Actions act= new Actions(driver);
Thread.sleep(2000);
act.moveToElement(Admin).moveToElement(job).moveToElement(jobtitles).click().build().perform();
WebElement AddBtn= driver.findElement(By.xpath(("//input[#value='Add']")));
Thread.sleep(2000);
AddBtn.click();
driver.findElement(By.xpath(("//*[#id='jobTitle_jobTitle']"))).sendKeys("Manager");
driver.findElement(By.xpath(("//*[#id='jobTitle_jobDescription']"))).sendKeys("zxc");
driver.findElement(By.xpath(("//*[#id='jobTitle_note']"))).sendKeys("jobTitle_note");
WebElement SaveBtn= driver.findElement(By.xpath(("//input[#value='Save']")));
Thread.sleep(2000);
SaveBtn.click();
return job;
}
#Test
public void PayGrade(WebElement job) throws InterruptedException
{
//WebElement job = driver.findElement(By.xpath("//*[#id='menu_admin_viewAdminModule']//following-sibling::ul/li[2]/a"));
WebElement payGrade = driver.findElement(By.xpath("//*[#id='menu_admin_viewAdminModule']//following-sibling::ul/li[2]/ul/li[2]/a"));
Actions act= new Actions(driver);
act.moveToElement(job).moveToElement(payGrade).click().build().perform();
WebElement AddPayBtn= driver.findElement(By.xpath(("//input[#value='Add']")));
Thread.sleep(2000);
AddPayBtn.click();
driver.findElement(By.xpath(("//*[#id='payGrade_name']"))).sendKeys("INR");
WebElement SavePayBtn= driver.findElement(By.xpath(("//input[#value='Save']")));
Thread.sleep(2000);
SavePayBtn.click();
}
#AfterTest
public void teardown()
{
driver.quit();
} }
In above code TestNG passing only one Test named as Login(). Can anyone tell me please why is it so?
How to improve this code and run all tests in a series.
When I run your code, I get the following log:
PASSED: login
FAILED: PayGrade
org.testng.TestNGException:
Cannot inject #Test annotated Method [PayGrade] with [interface org.openqa.selenium.WebElement].
For more information on native dependency injection please refer to https://testng.org/doc/documentation-main.html#native-dependency-injection
I do not think put WebElement job as parameter of PayGrade(WebElement job) is right, so try to fix this kind of codes.
EDIT 1:
Details in code comments:
package hrmInfoModule;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Hrmlogin {
public WebDriver driver;
/*
* put common xpath string here
*/
String xJob = "//a[#id='menu_admin_Job']";
String xJobTitles = "//a[#id='menu_admin_viewJobTitleList']";
String xPayGrade = "//a[#id='menu_admin_viewPayGrades']";
#BeforeTest
public void openbrowser() {
System.setProperty("webdriver.chrome.driver", "D:\\Software\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
#Test (priority = 0)
public void testLogin() throws InterruptedException {
String Url = "https://opensource-demo.orangehrmlive.com/";
String ID = "Admin";
String Pswrd = "admin123";
driver.get(Url);
WebElement login = driver.findElement(By.id("txtUsername"));
login.sendKeys(ID);
WebElement paswrd = driver.findElement(By.id("txtPassword"));
paswrd.sendKeys(Pswrd);
WebElement btn = driver.findElement(By.id("btnLogin"));
btn.click();
Thread.sleep(2000);
}
#Test (priority = 1)
public void testAdmin() throws InterruptedException {
WebElement admin = driver.findElement(By.xpath(("//*[#id='menu_admin_viewAdminModule']")));
/**
* Notice:
* 1. If there are no effective steps in this function, it should be removed.
* 2. click() is more stable than Actions.moveTo()
*/
admin.click();
Thread.sleep(2000);
}
#Test (priority = 2)
public void testJobTitle() throws InterruptedException {
Thread.sleep(2000);
WebElement job = driver.findElement(By.xpath(xJob));
WebElement jobTitles = driver.findElement(By.xpath(xJobTitles));
Actions act = new Actions(driver);
Thread.sleep(2000);
act.moveToElement(job).moveToElement(jobTitles).click().build().perform();
WebElement AddBtn = driver.findElement(By.xpath(("//input[#value='Add']")));
Thread.sleep(2000);
AddBtn.click();
driver.findElement(By.xpath(("//*[#id='jobTitle_jobTitle']"))).sendKeys("Manager");
driver.findElement(By.xpath(("//*[#id='jobTitle_jobDescription']"))).sendKeys("zxc");
driver.findElement(By.xpath(("//*[#id='jobTitle_note']"))).sendKeys("jobTitle_note");
WebElement SaveBtn = driver.findElement(By.xpath(("//input[#value='Save']")));
SaveBtn.click();
Thread.sleep(2000);
}
#Test (priority = 3)
public void testPayGrade() throws InterruptedException {
WebElement job = driver.findElement(By.xpath(xJob));
WebElement payGrade = driver.findElement(By.xpath(xPayGrade));
Actions act = new Actions(driver);
act.moveToElement(job).moveToElement(payGrade).click().build().perform();
WebElement AddPayBtn = driver.findElement(By.xpath(("//input[#value='Add']")));
Thread.sleep(2000);
AddPayBtn.click();
driver.findElement(By.xpath(("//*[#id='payGrade_name']"))).sendKeys("INR");
WebElement SavePayBtn = driver.findElement(By.xpath(("//input[#value='Save']")));
Thread.sleep(2000);
SavePayBtn.click();
}
#AfterTest
public void teardown() {
driver.quit();
}
}

Selenium null pointer exception, when trying to use constructor

I created a class which has page objects defined in it. Then I am trying to use that class in a test class by using a constructor. However when I run the test class using JUnit I am getting a NullPointerException error.
Page_Objects Class:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.Select;
public class Page_Objects {
private WebDriver driver;
WebElement Username = driver.findElement(By.id("username"));
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
WebElement Password = driver.findElement(By.id("password"));
WebElement Login_Button = driver.findElement(By.id("Login"));
WebElement Logout_Button = driver.findElement(By.linkText("Logout"));
}
Test Class:
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Salesforce_Test {
private WebDriver driver1;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
Page_Objects pageobjects = new Page_Objects();
#Before
public void setUp() throws Exception {
driver1 = new FirefoxDriver();
baseUrl = "some url for testing/";
driver1.navigate().to(baseUrl);
driver1.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void Login_Logout() throws Exception {
pageobjects.Username.sendKeys("someusername");
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
pageobjects.Password.sendKeys("somepassword");
pageobjects.Login_Button.click();
pageobjects.Logout_Button.click();
}
#After
public void tearDown() throws Exception {
driver1.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver1.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver1.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver1.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
When I run the above class I get a null pointer exception.
java.lang.NullPointerException
at Page_Objects.<init>(Page_Objects.java:20)
at Salesforce_Test.<init>(Salesforce_Test.java:16)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
I see two issues here. First is that the Page_Objects class is called before you initiated the driver. That's why when you're calling
Page_Objects pageobjects = new Page_Objects();
you're getting a NullPointerException.
So you want to initiate the Page_Objects after you've initiated the driver.
Second, you need to pass it the instance of the driver you've initiated, because right now it has its own Private driver which isn't initiated and therefore it's null.
So in short:
Initiate Page_Objects after you've initiated driver (after the driver1 = new FirefoxDriver(); line)
Call it with the driver you've initiated: Page_Objects pageobjects = new Page_Objects(driver1 );

Categories

Resources