I am having an issue with this class where I am receiving a null pointer exception. I inserted System.out.println("driver=" + driver); to see what is outputted and it states the driver=null for each dataset which makes me think there is a problem with the initialization when I hit the method under #Test. How can I resolve this initialization of the driver to get my tests to pass in testNG?
Below is the code:
package com.testng.practice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class LoginTest {
WebDriver driver = null;
#BeforeTest
public void invokeApplication() {
System.setProperty("webdriver.chrome.driver", "xxx\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.facebook.com");
}
#Test (dataProvider = "getData")
public void loginFaceBook(String email, String password) {
System.out.println("driver=" + driver);
WebElement emailField = driver.findElement(By.name("email"));
WebElement passwordField = driver.findElement(By.name("pass"));
emailField.sendKeys(email);
passwordField.sendKeys(password);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#DataProvider
public Object[][] getData(){
//declared object of 4 rows and 2 columns
Object[][] dataSet = new Object[4][2];
dataSet[0][0] = "TimSmith#gmail.com";
dataSet[0][1] = "Smith123";
dataSet[1][0] = "JaneMcCormack#gmail.com";
dataSet[1][1] = "McCormack123";
dataSet[2][0] = "AnjaliPrakash#gmail.com";
dataSet[2][1] = "Prakash123";
dataSet[3][0] = "JamesBean#gmail.com";
dataSet[3][1] = "Bean123";
return dataSet;
}
}
This definition of the driver variable is valid within the invokeApplication() method and leaves the class attribute driver uninitialized
WebDriver driver = new ChromeDriver();
to initialize the class attribute use:
this.driver = new ChromeDriver();
I think the problem should be in the #BeforeTest annotation if you are running the class it self by running as TestNG.
BeforeTest annotation is working before the tag in the xml runner file.
Here is the definition of BeforeTest from TestNG documentation.
#BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run.
If you want to run before #Test you need to use #BeforeMethod.
Please pay attentionto the differences between all the annotation.
You can find differences here.
you declare WebDriver driver=null; Globally.
Then No Need To Declare once in Method invokeApplication();
write only
WebDriver driver = null;
#BeforeTest
public void invokeApplication() {
System.setProperty("webdriver.chrome.driver", "xxx\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.facebook.com");
Related
I'm trying to achieve parallel execution through data provider, but unable to do it. can someone help me with this.
The error is two browsers are opening but the data is going to only one browser.
Here, is my program code:
package PracticePrograms;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DataProviderSample1{
public WebDriver driver;
#BeforeMethod
public void setUp() throws InterruptedException {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(6));
driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
}
#Test(dataProvider = "inputData")
public void testLogin(String UserName, String Password ) throws InterruptedException {
driver.findElement(By.name("username")).sendKeys(UserName);
driver.findElement(By.name("password")).sendKeys(Password);
driver.findElement(By.xpath("//button[#type='submit']")).click();
}
#DataProvider(name = "inputData", parallel = true)
public static Object[][] loginData() {
Object[][] data = new Object[2][2];
data[0][0] = "Admin";
data[0][1] = "admin123";
data[1][0] = "admin";
data[1][1] = "admin123";
return data;
}
#AfterMethod
public void tear_down() throws InterruptedException {
driver.quit();
}
}
I appreciate u r help on this.
Despite your method logic runs in parallel all your threads still use the same instance of your test class. Hence they share the same instance of your driver field.
This leads to the case when the setUp() executed "after" overwrites the value set by setUp that has been executed "before"..
So to overcome this you need to introduce ThreadLocal variable. Instead of public WebDriver driver; you would have ThreadLocal<WebDriver> driver = new ThreadLocal<>();
Now instead of driver = new FirefoxDriver(); you would have driver.set( new FirefoxDriver());
After you have set that driver to ThreadLocal, wherever you obtain its value you have to do driver.get(). For example:
driver.get().manage().deleteAllCookies();
driver.get().manage().timeouts().implicitlyWait(Duration.ofSeconds(6));
driver.get().get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
I'm a beginner Selenium practitioner. I have 2 classes, one for the WebDriver another is for Log In. I followed some youtube tutorials but can't pinpoint what I'm doing wrong. I tried the concept of 'Baseclass' where I extend the other class.
LogIn Class
WebDriver Class
If I add the WebDriver in the other class, it will run successfully. But I want to make it more 'organized'
this is the error
Error message
public Webdriver driver;
Please add static in this line
public static Webdriver driver;
because you need use same driver instance for all classes
create above line in top of both classes
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.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
public class TestApp {
private WebDriver driver;
private static TestApp myObj;
// public static WebDriver driver;
utils.PropertyFileReader property = new PropertyFileReader();
public static TestApp getInstance() {
if (myObj == null) {
myObj = new TestApp();
return myObj;
} else {
return myObj;
}
}
//get the selenium driver
public WebDriver getDriver()
{
return driver;
}
//when selenium opens the browsers it will automatically set the web driver
private void setDriver(WebDriver driver) {
this.driver = driver;
}
public static void setMyObj(TestApp myObj) {
TestApp.myObj = myObj;
}
public void openBrowser() {
//String chromeDriverPath = property.getProperty("config", "chrome.driver.path");
//String chromeDriverPath = property.getProperty("config", getChromeDriverFilePath());
System.setProperty("webdriver.chrome.driver", getChromeDriverFilePath());
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void navigateToURL() {
String url =property.getProperty("config","url");
;
driver.get(url);
}
public void closeBrowser()
{
driver.quit();
}
public WebElement waitForElement(By locator, int timeout)
{
WebElement element = new WebDriverWait(TestApp.getInstance().getDriver(), timeout).until
(ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
private String getChromeDriverFilePath()
{
// checking resources file for chrome driver in side main resources
URL res = getClass().getClassLoader().getResource("chromedriver.exe");
File file = null;
try {
file = Paths.get(res.toURI()).toFile();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
}
//create package name called utils and under that package create class name with TestApp and paste above code
if you want use driver anywhere in your project
TestApp.getInstance().getdriver();
You didn't initialize your driver anywhere.
You need to use a before
#BeforeClass
public void setupClass(){
driver = new Chromedriver();
}
and in opensite
public static WebDriver driver;
You want your OpenSite class to act as the base class which you can extend it to your test class to intialize your driver. Remove your "#test" annotaion from the OpenSite class.
Add static with "public WebDriver driver";
Create a method openBrowser(already there) or driverInitialization in this class.
Return the driver instance.
Updated code will look like
public class OpenSite{
public static WebDriver driver;
public static void openBrowser(){
System.setProperty("webdriver","path");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("your URL");
return driver;
}
}
And in test class LogIn extend this class and call this method:
public class LogIn extends OpenSite{
#BeforeTest
public void driver initialization(){
openBrowser();
}
#Test
public void logInVendor(){
//Write your code here
}
}
I am trying to run some basic tests using Selenium Grid and I acquired the code below from my instructor.
However RemoveWebDriver driver is always NULL as device is always param-value-not-found
I am unable to understand what is setting the value of the parameter device and how to correct this error.
My knowledge of TestNG is limited. I am guessing TestNG is responsible for calling the openBrowser function which has a parameter device the value of this parameter is always param-value-not-found.
Therefore in the if else block device does not equal pc1 or pc2 which causes driver vairable to have a value Null.
I am unable to figure out how the value of device is getting derived.
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class gridTest
{
public static WebDriver driver ;
#Parameters("System")
#Test(priority=0)
public void openBrowser(String device) throws MalformedURLException // device is always param-value-not-found
{
System.out.println("device is : " + device);
if (device.equalsIgnoreCase("pc1"))
{
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability("browserVersion", "80");
driver = new RemoteWebDriver(new URL("http://192.168.1.6:30032/wd/hub"), cap);
}
else if (device.equalsIgnoreCase("pc2"))
{
DesiredCapabilities cap = DesiredCapabilities.firefox();
driver = new RemoteWebDriver(new URL("http://192.168.1.6:30032/wd/hub"), cap);
// adding the following else block merely bypasses the issue
} else {
String nodeUrl = "http://192.168.1.6:30032/wd/hub" ;
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setBrowserName("chrome");
capabilities.setPlatform(Platform.WINDOWS);
driver = new RemoteWebDriver(new URL(nodeUrl), capabilities);
}
}
#Test(priority = 1)
public void Moda()
{
try
{
//Navigate to URL
driver.get("https://www.flipkart.com/");
driver.manage().window().maximize();
}
catch (Exception e)
{
System.out.println(e);
return;
}
// Close login modal screen
driver.findElement(By.xpath("//*[#class='_2AkmmA _29YdH8']")).click();
// Hover the menu Electronics >> MI
WebElement men1 = driver.findElement(By.xpath("//li[#class='Wbt_B2 _1YVU3_'][1]"));
Actions act = new Actions(driver);
act.moveToElement(men1).perform();
Thread.sleep(2000);
WebElement men2 = driver.findElement(By.xpath("//li[#class='_1KCOnI _3ZgIXy'][1]//a[contains(#href,'Electronics_0_Mi')]"));
men2.click();
//Verify 'Latest from MI' label on the search result page
try
{
Thread.sleep(3000);
}
catch(InterruptedException ie){
System.out.println("Error at line 76") ;
}
boolean Validate = driver.findElement(By.xpath("//p[text()='Latest from MI : ']")).isDisplayed();
System.out.println("Latest from MI element is displayed--" + Validate);
System.out.println("Completed.") ;
}
}
This means that your test expects to have System parameter value in your testng.xml file. You have to either add one or add #Optional annotation to your method parameter so that the parameter would have been set to that optional value if no values are detected in testng.xml.
See details here.
I am starting learning Selenium in Java and I have a big obstacle.
import org.junit.After;
import org.junit.Before;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FirstTest {
WebDriver driver;
#Before
public void driverSetup() {
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().setSize(new Dimension(1280, 720));
}
#After
public void driverQuit() {
driver.quit();
}
#Test
public void getMethod() {
driver.get("http://google.pl");
}
}
I don't know how to solve it because in "getMethod" the driver is NULL.
You have defined WebDriver driver; at the global level and then you are again defining and instantiating another WebDriver driver in the driverSetup method because of which the global driver never got instantiated.
You need to make a single line change in the driverSetup method and it would work.
Your driverSetup should be like:
#Before
public void driverSetup() {
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
// Instantiating the global driver here
driver = new ChromeDriver();
driver.manage().window().setSize(new Dimension(1280, 720));
}
You were close. You have already defined an instance of WebDriver i.e. driver as a global instance as in:
WebDriver driver;
You can reuse the same instance in #Before, #Test and #After. So there is no need to declare any additional instace of WebDriver in #Before as you did:
WebDriver driver = new ChromeDriver();
Solution
The solution will be to use the same global WebDriver instance as follows:
WebDriver driver;
#Before
public void driverSetup() {
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().setSize(new Dimension(1280, 720));
}
" Here is the code of selenium web driver in which i use POM design to define all the locators of the web page. So after running the code i got an error regarding the null pointer exception.
"
{
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
WebDriver driver;
By username = By.id("user_login");
By password = By.id("user_pass");
By login = By.id("wp-submit");
By rememberme = By.id("rememberme");
public LoginPage(WebDriver driver){
this.driver = driver;
}
public void typeusername(){
driver.findElement(username).sendKeys("admin");
}
public void typepassword(){
driver.findElement(password).sendKeys("demo123");
}
public void clickrememberme(){
driver.findElement(rememberme).click();
}
public void clicklogin(){
driver.findElement(login).click();
}
}
"Here in this code i created an object of a login page and call all the locators using TestNG annotations."
{
package Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import Pages.LoginPage;
public class verifylogin {
#BeforeTest
public void beforetest(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\saniket.soni\\Desktop\\chrome\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demosite.center/wordpress/wp-login.php");
}
#Test
public void verifyvalidlogin(){
WebDriver driver = null;
LoginPage login_test = new LoginPage(driver);
login_test.typeusername();
login_test.typepassword();
login_test.clickrememberme();
login_test.clicklogin();
}
}
You might want to consider studying scope in java to understand what is happening in this issue. Here is an explanation for what is happening in your case.
In your public void beforetest() method, you're creating a driver, and using it, but when that method is done the driver variable goes out of scope, and you no longer have access to it.
Later, in your verifyValidLogin method, you're creating a new driver variable, and setting it to null:
WebDriver driver = null;
Then you pass this null driver to your LoginPage here:
LoginPage login_test = new LoginPage(driver);//driver is null here
So when you use it here:
public LoginPage(WebDriver driver){
this.driver = driver;
}
public void typeusername(){
driver.findElement(username).sendKeys("admin");
}
It's null
Try making these changes:
First, save your driver somewhere when you initialize it like this:
public class verifylogin {
//STORE YOUR DRIVER SOMEWHERE!!! Like here
private WebDriver driver;
#BeforeTest
public void beforetest(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\saniket.soni\\Desktop\\chrome\\chromedriver.exe");
//Store the driver in the class variable
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demosite.center/wordpress/wp-login.php");
}
#Test
public void verifyvalidlogin(){
//Now you can use the driver you stored
LoginPage login_test = new LoginPage(driver);
login_test.typeusername();
login_test.typepassword();
login_test.clickrememberme();
login_test.clicklogin();
}
You are removing object reference by using "WebDriver driver = null" in verifyvalidlogin() method. Remove this line and try, it will work.
You instance variable 'driver' as private ('private WebDriver driver').
With 'private' access modifier you can access driver within the class but not from outside, change it to public it will work.
In beforetest() method you are instantiating the browser object and navigating to demo Url.
After that in verifyvalidlogin() method you are making driver object to null and passing this null object to Login page, here you are passing null instead of driver object.
We can solve this issue by declaring driver instance variable inside the class and outside of all methods like below.
WebDriver driver;
Instantiate this driver object in beforetest() method and pass the same driver object to LoginPage without declaring it again as mentioned below.(I executed this script in my local machine its working fine)
package Tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import Pages.LoginPage;
public class verifylogin {
WebDriver driver;
#BeforeTest
public void beforetest(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\saniket.soni\\Desktop\\ chrome\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demosite.center/wordpress/wp-login.php");
}
#Test
public void verifyvalidlogin(){
LoginPage login_test = new LoginPage(driver);
login_test.typeusername();
login_test.typepassword();
login_test.clickrememberme();
login_test.clicklogin();
}
}
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
WebDriver driver;
By username = By.id("user_login");
By password = By.id("user_pass");
By login = By.id("wp-submit");
By rememberme = By.id("rememberme");
public LoginPage(WebDriver driver){
this.driver = driver;
}
public void typeusername(){
driver.findElement(username).sendKeys("admin");
}
public void typepassword(){
driver.findElement(password).sendKeys("demo123");
}
public void clickrememberme(){
driver.findElement(rememberme).click();
}
public void clicklogin(){
driver.findElement(login).click();
}
}
Try this solution and let me know if it works for you.