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));
}
Related
when I try to run below code in testNg null pointer exception shown in Eclipse
public class ImgDDChkbxRadio {
WebDriver driver;
#BeforeTest
public void LaunchBrowser()
{
System.setProperty("webdriver.chrome.driver","F:\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.leafground.com/");
}
#Test
public void Img()
{
driver.findElement(By.xpath("//img[#src='images/image.png']")).click();
driver.findElement(By.xpath("//*[#src=\"../images/home.png\"]")).click();
driver.navigate().back();
driver.findElement(By.xpath("//*[#src=\"../images/abcd.jpg\"]")).click();
}
}
Just remove the WebDriver from LaunchBrowser() and I hope this
will work for you ;)
public class ImgDDChkbxRadio {
WebDriver driver;
#BeforeTest
public void LaunchBrowser()
{
System.setProperty("webdriver.chrome.driver","/Users/chrome/chromedriver");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.leafground.com/");
}
#Test
public void Img()
{
driver.findElement(By.xpath("//img[#src='images/image.png']")).click();
driver.findElement(By.xpath("//*[#src=\"../images/home.png\"]")).click();
driver.navigate().back();
driver.findElement(By.xpath("//*[#src=\"../images/abcd.jpg\"]")).click();
}
}
I've learned since I've made this comment.
My new suggestion is - delete all imports at the beginning of your file and add them again. Be cautious about proper imports - especially versions of your test suite - issue can occur when code uses few different versions.
How to add imports? Move your cursour over marked classes, methods, etc. and react accordingly to your IDE suggestions (Alt + Enter for IntelliJ for Windows).
OLD and probably unsafe workaround:
My old suggestion can be a workaround for your issue but could make a lot of new instances and I guess it's not a wise thing to do. Tests will work but more like a by-product.
Create an instance of ChromeDriver before using it in your LaunchBrowser() method:
public class ImgDDChkbxRadio {
WebDriver driver = new ChromeDriver();
#BeforeTest
public void LaunchBrowser()
{
System.setProperty("webdriver.chrome.driver","F:\\chromedriver_win32\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.leafground.com/");
}
#Test
public void Img()
{
driver.findElement(By.xpath("//img[#src='images/image.png']")).click();
driver.findElement(By.xpath("//*[#src=\"../images/home.png\"]")).click();
driver.navigate().back();
driver.findElement(By.xpath("//*[#src=\"../images/abcd.jpg\"]")).click();
}
}
I think it may be the result of some changes made in JUnit 5 in annotations (#).
It could be the the site is not being loaded - are you able to launch the site manually?
If yes try this:
Make WebDriver object static (write static before the variable name)
Try to add Thread.Sleep(5000) to LaunchBrowser method, after you open the site using the browser
You are creating an object of the Browser with the help of the WebDriver Interface.
WebDriver{ driver = new new EdgeDriver();}
but the scope of this driver is within method only. To use it, you declared it publicly.
The lifetime of the driver is only in the WebDriver interface.
Making it: driver=new EdgeDriver();
can only solve your issues:
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.findElement(org.openqa.selenium.By)" because "this.driver" is null
package ADUMMYExersice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class stackoverflowNull {
WebDriver driver;
#BeforeTest
public void LaunchBrowser()
{
System.setProperty("webdriver.edge.driver", "C:\\Selenium Files\\BrowserExe\\msedgedriver.exe");
driver=new EdgeDriver();
driver.manage().window().maximize();
driver.get("http://www.leafground.com/");
}
#Test
public void Img()
{
driver.findElement(By.xpath("//img[#src='images/image.png']")).click();
driver.findElement(By.xpath("//*[#src=\"../images/home.png\"]")).click();
driver.navigate().back();
driver.findElement(By.xpath("//*[#src=\"../images/abcd.jpg\"]")).click();
}
}
I had simular problem.
I changed
"WebDriver driver" to
"public static Webdriver".
This worked by me.
It could be an issue with your Chrome browser too - try it with Firefox and still does not work then try to change your workspace.
Had the same issue wasted 6hrs trying and searching. worked for me with Firefox.
protected static WebDriver driver;
use above and check if you have used web driver in any other class ?
I had two classes and in that I gave a variable name as public WebDriver driver; but it did not work it throwed me a error message saying
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.findElement(org.openqa.selenium.By)" because "this.driver" is null.
After that I found an answer which we need to give static before the variable public static WebDriver driver;
We I have create a test script and using testing I have facing center code here` that kind of problem Please Check my code and resolved my Prblem
package testcase;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import base.Basetest;
public class MyFirstTestFW extends Basetest{
#Test
public static void LoginTest() throws InterruptedException
{
System.out.println("Clicked Successfully");
driver.findElement(By.linkText("Sign in")).click(); //locals----properties
driver.findElement(By.id("login_id")).sendKeys("vaishali.verma#techinfini.in");
driver.findElement(By.xpath("//span[normalize-space()='Next']")).click();
Thread .sleep(4000);
driver.findElement(By.xpath("//input[#id='password']")).sendKeys("Vaishu#123");
Thread .sleep(4000);
driver.findElement(By.xpath("//button[#id='nextbtn']//span[contains(text(),'Sign in')]")).click();
Thread .sleep(4000);
}
}
I have a test in Selenium WebDriver with Page Object Model, if I run the following test open two windows in the Chrome browser, first window is empty in a URL line. How I can opening only one with onet.pl URL?
I trying deleting initialize Chrome driver but will have null.exception error.
What am I doing wrong?
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
public class LoginPage {
private WebDriver driver;
//private WebDriverWait wait;
public LoginPage() {
this.driver = new ChromeDriver();
//wait = new WebDriverWait(driver,10);
}
#FindBy(xpath="//div[#class='col-md-12']//form")
private WebElement loginForm;
#FindBy(id="username")
private WebElement loginField;
#FindBy(id="password")
private WebElement passwordField;
#FindBy(xpath="//button[#class='btn btn-multisport-default btn-multisport-large btn-full-width login-button']")
private WebElement buttonLogin;
public void open() {
driver.get("https://onet.pl");
}
public void enterLogin() {
String login = "vadim1234#test.pl";
loginField.sendKeys(login);
}
public void enterPassword() {
String password = "Benefit!";
passwordField.sendKeys(password);
}
public void login() {
buttonLogin.click();
}
}
And test code:
import Pages.Dashboard;
import Pages.LoginPage;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import java.util.concurrent.TimeUnit;
public class LogIn {
#Test
public void correctLogin() {
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
WebDriver driver = new ChromeDriver();
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
loginPage.open();
loginPage.enterLogin();
loginPage.enterPassword();
loginPage.login();
driver.close();
driver.quit();
Dashboard dashboard = new Dashboard(driver);
dashboard.getLoggedUser();
}
}
From your test class as you are passing the reference of the driver:
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
In LoginPage class, within the constructor, instead of:
public LoginPage() {
this.driver = new ChromeDriver();
//wait = new WebDriverWait(driver,10);
}
you need to do reuse the instance passed as follows:
public LoginPage(WebDriver loginPageDriver) {
this.driver=loginPageDriver;
}
That would solve the issue of 2 browsers getting opened.
References
You can find a couple of relevant detailed discussions in:
Selenium [Java] PageFactory Design : Where do I write my Assertions following Page Object Model
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");
" 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.
Hi Im a newbie to selenium, i was trying to use TestNG with IE webdriver, Now i cant instantiate the IE driver directly under the class (Not the main method). When i do that i get the below error:
Multiple markers at this line
- Syntax error on tokens, FormalParameter expected instead
- Syntax error on token(s), misplaced construct(s)
- Syntax error on token ""webdriver.ie.driver"", invalid
If i then put on a method with #BeforeSuite annotation, i need to pass the driver to every other test method in the class. Is there a way where i can by pass this passing the driver object.
Find below the sample code i am using:
package FirstTestNGPackage;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class FirstTestNGclass {
#BeforeSuite
public void SetDriverPaths()
{
File IEDriver = new File("C:\\Users\\REDACTED\\Desktop\\SeleniumJars\\IE Driver\\IEDriverServerX64_2.44.0.exe");
System.setProperty("webdriver.ie.driver", IEDriver.getAbsolutePath());
WebDriver Driver = new InternetExplorerDriver();
}
#Test
public void tester()
{
Driver.findElement(By.id("keywordInput")).sendKeys("REDACTED");
Driver.findElement(By.id("keywordInput")).sendKeys(Keys.ENTER);
Assert.assertEquals(Driver.findElement(By.xpath(".//*[#id='search_results']/h1/span/strong")).getText(), "REDACTED");
}
#BeforeTest
public void RMSLogin()
{
Driver.navigate().to("REDACTED");
}
#AfterTest
public void closeBrowser()
{
Driver.quit();
}
}
init you webdriver like this then you can use it in every method with this.driver.
public class FirstTestNGclass {
public WebDriver driver;
#BeforeSuite
public void SetDriverPaths()
{
// ....
this.driver = new InternetExplorerDriver();
}
// ....
}
One of the simple solution to this problem is to use a common driver class for your Test suite...so that we can use the same driver instance in all classes
Common driver class
public class Driver {
public static WebDriver driver=null;
public static WebDriver startdriver(String browser){
if(browser.equalsIgnoreCase("Chrome")){
System.setProperty("webdriver.chrome.driver", "path");
driver=new ChromeDriver();
}else if(browser.equals("IE")){
System.setProperty("webdriver.ie.driver", IEDriver.getAbsolutePath());
driver=new InternetExplorerDriver();
}
return driver;
}
}
you can create a driver instance like this
Driver.startdriver("IE");
You can use the driver object like classname.instance
Driver.driver.findElement(By.xpath("path"));
Hope this helps you...if you have any queries Kindly get back