I wrote code like this but this code isn't running the chromedriver and i have added the file(chromedriver.exe) with this path (\chromedrive\chromedriver.exe).
public class Browser {
private static WebDriver driver = new ChromeDriver();
public static WebDriver driver() {
return driver;
}
public static void open(String url) {
String path = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver",path + "\\chromedrive\\chromedriver.exe");
driver.manage().window().maximize();
driver.get(url);
}
}
.
public class Page extends LoadableComponent<Page> {
static String url = "http://-------";
private static String title = "title";
public Page() {
PageFactory.initElements(Browser.driver(), this);
}
#Override
protected void load() {
// TODO Auto-generated method stub
Browser.open(url);
}
#Override
protected void isLoaded() throws Error {
// TODO Auto-generated method stub
assertTrue(Browser.driver().getTitle().equals(title));
}
}
.
public class PageTests {
#Test
public void pageTest() {
Page page = new Page();
page.get();
}
}
The error message is:
java.lang.ExceptionInInitializerError
Caused by: java.lang.IllegalStateException: The path to the driver
executable must be set by the webdriver.chrome.driver system property;
Initially i think you are creating the Chromedriver, without the reference to the exe being there.
So if you change it into something like this, it will probaly work.
public class Browser {
private static WebDriver driver;
public static WebDriver driver() {
return driver;
}
public static void open(String url) {
String path = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver",path + "\\chromedrive\\chromedriver.exe");
driver = new ChromeDriver(); //Initilize here
driver.manage().window().maximize();
driver.get(url);
}
}
When your application loads the first time, it'll try to load the Browser class.
While loading a class the JVM will do all the static initializing that is specified, in this case it'll try to create a ChromeDriver object, because you're initializing the static field with new ChromeDriver(). At that point your open method hasn't been called yet to set the system property, so an exception will be thrown, which causes the JVM to quit.
To fix this, either create the ChromeDriver object /after/ setting the system property (e.g. in your open method) or set the system property when starting the JVM:
java -Dwebdriver.chrome.driver=path/to/driver -jar somejar.jar
You should instantiate you browser inside the function you are defining and setting the path.
try this:
public static void open(String url) {
String path = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver",path + "\\chromedrive\\chromedriver.exe");
driver.manage().window().maximize();
WebDriver driver = new ChromeDriver();
driver.get(url);
}
There is no need of separately creating a driver function.please remove it.
Related
public class WorkingWithChrome {
ChromeDriver driver;
String url = "https://www.alfasoft.pt/";
public void invokeBrowser() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\fabio\\eclipse-workspace\\libs\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
}
public static void main(String[] args) {
WorkingWithChrome wc = new WorkingWithChrome();
wc.invokeBrowser();
//wc.closeBrowser();
}
public void TitleTest() throws Exception {
String Url = "https://www.alfasoft.pt/";
String TituloEsperado = "Alfasoft";
String TituloAtual = "";
driver.get(Url);
TituloAtual = driver.getTitle();
if (TituloAtual.contains(TituloEsperado)) {
System.out.println("Titulo Correto!");
} else {
System.out.println("Titulo Errado!");
}
driver.quit();
}
}
The page open's but I think that the part of the code that is suposed to check the title is not working because the webpage never closes. I just started using selenium, trying to learn it to use it on the current company that Im working at.
Currently in the main method you only invoking wc.invokeBrowser(); but not invoking the TitleTest() method where you calling the driver.quit();
To invoke TitleTest() just put it in main() method as following:
public static void main(String[] args) {
WorkingWithChrome wc = new WorkingWithChrome();
wc.invokeBrowser();
wc.TitleTest();
}
BTW, it's a convention in JAVA to give methods names starting with lowercase so it should be named titleTest() rather than TitleTest()
Can someone tell the issue in my code for null pointer exception?
Error Message in console
=>test.pages.HomePage#31e75d13<=
[31mFailed scenarios:[0m
[31mE2E_Test.feature:3 [0m# Scenario: Test scenario
1 Scenarios ([31m1 failed[0m)
10 Steps ([31m1 failed[0m, [36m8 skipped[0m, [32m1 passed[0m)
0m12.461s
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.$Proxy17.sendKeys(Unknown Source)
at test.pages.HomePage.enterSearchText(HomePage.java:31)
at stepDefinitions.Steps.he_search_for(Steps.java:49)
at ✽.When he search for "test"(E2E_Test.feature:5)
Although I am getting the driver object and its not coming as Null as well but still getting a null pointer exception.
I am trying to run the selenium webdriver code to automate some test case. Here i am trying to open google.com and wants to enter some text in search box but after opening the google.com, when the execution reaches searchtextbox.sendkeys("test"), it gives null pointer exception. I tried debugging it to see if the homepage class object is coming as null or not but its showing the value and not null.
This is the test base class that i am using to initiate the google site and maximize the code
public class TestBase {
public static WebDriver driver;
public static Properties prop;
public static EventFiringWebDriver e_driver;
public static WebEventListener eventListener;
public TestBase() {
try {
prop = new Properties();
FileInputStream ip = new FileInputStream(System.getProperty("user.dir") + "/src/main/java/test" +
"/config/config.properties");
prop.load(ip);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// This method is used to initiatize the site url
public static void initialization(String url) {
String browserName = prop.getProperty("browser");
if (browserName.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\test\\Downloads\\driver\\chromedriver.exe");
driver = new ChromeDriver();
}
e_driver = new EventFiringWebDriver(driver);
// Now create object of EventListerHandler to register it with EventFiringWebDriver
eventListener = new WebEventListener();
e_driver.register(eventListener);
driver = e_driver;
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT, TimeUnit.SECONDS);
if (url == "google") {
driver.get(prop.getProperty("url"));
}
}
}
// Steps Definition file (Steps.java): This is the step defintion file // there is a function he_search_for called where the exception occurs
public class Steps extends TestBase {
WebDriver driver;
TestUtil testUtil;
HomePage homePage;
#Given("^user is on google home page$")
public void user_is_on_google_home_page() throws Throwable {
initialization("google");
testUtil = new TestUtil();
homePage = new HomePage(driver);
}
#When("^he search for \"([^\"]*)\"$")
public void he_search_for(String arg1) throws InterruptedException {
System.out.print("=>" + homePage + "<=");
homePage.enterSearchText();
}
}
// HomePage Class is used to define all the page elements here in this class, i used enterSearchText function to enter the text in a search box.
public class HomePage extends TestBase {
#FindBy(name = "q")
WebElement searchTextBox;
WebDriver driver;
// Initializing the Page Objects:
public HomePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void enterSearchText() {
searchTextBox.sendKeys("Test");
}
}
Problem lies within your code design pattern between Classes Steps & TestBase. Please note
First, Class Steps is extending TestBase which already has WebDriver variable declared & initialized in it. So you do not need to again define WebDriver instance with in Steps. So please remove "WebDriver driver;" from below peace of code.
public class Steps extends TestBase {
WebDriver driver;
TestUtil testUtil;
Second, Please do not declare WebDriver as static variable. Kindly declare it as Non-static as Keeping static may create problem during parallel execution as well.
public class TestBase {
public WebDriver driver;
Making WebDriver instance as non-static and having it as Thread safe
TestBase.java
public class TestBase {
public WebDriver driver;
public static Properties prop;
// This method is used to initiatize the site url
public synchronized void initialization(String url) {
String browserName = prop.getProperty("browser");
if (browserName.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\test\\Downloads\\driver\\chromedriver.exe");
driver = new ChromeDriver();
DriverManager.setWebDriver(driver);
}
}
}
DriverManager.java
import org.openqa.selenium.WebDriver;
public class DriverManager {
public static ThreadLocal<WebDriver> dr = new ThreadLocal<WebDriver>();
public static WebDriver getDriver() {
return dr.get();
}
public static void setWebDriver(WebDriver driver) {
dr.set(driver);
}
}
The problem is here
public class Steps extends TestBase {
WebDriver driver;
TestUtil testUtil;
HomePage homePage;
#Given("^user is on google home page$")
public void user_is_on_google_home_page() throws Throwable {
initialization("google");
testUtil = new TestUtil();
homePage = new HomePage(driver);
}
#When("^he search for \"([^\"]*)\"$")
public void he_search_for(String arg1) throws InterruptedException {
System.out.print("=>" + homePage + "<=");
homePage.enterSearchText();
}
}
The WebDriver driver is null. You initialized WebDriver in initialization("google") method but you don't assign the value of created WebDriver to your driver
Additional line of code might help you.
#Given("^user is on google home page$")
public void user_is_on_google_home_page() throws Throwable {
initialization("google");
this.driver = TestBase.driver; //asign initialized WebDriver to this instance variable
testUtil = new TestUtil();
homePage = new HomePage(driver);
}
You can also remove the local WebDriver driver variable. Since TestBase contains static WebDriver, you can just use it directly since you use inheritance.
However, I highly suggest reading about WebDriverFactory or any similar term, like WebDriverManager. Anything to handle WebDriver instantiation without creating a static WebDriver. It will cause a lot of issues in the future with parallel execution.
My program works fine when run from my local machine with out using selenium grid with Remote Web driver. However when i set up the same test cases using selenium grid with Remote Web driver . Get message in eclipse saying:
java.lang.NullPointerExceptionat PP_OBJ_Login.Adminlogin(PP_OBJ_Login.java:38)
at PP_Main.step01_Login(PP_Main.java:86)
Now I know the above means that line 38 and line 86 is where the problem is in both classes my problem is i don't know why this is happening when I use selenium grid with Remote Web driver.
public class PP_Main {
private static WebDriver driver;
private static String homeUrl;
//private String homeTitle ="Google";
#SuppressWarnings("unused")
private boolean acceptNextAlert = true;
private static StringBuffer verificationErrors = new StringBuffer();
#BeforeClass
public static void setUp() throws Exception {
//----------This works and envokes IE browser -------
System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability(CapabilityType.BROWSER_NAME, DesiredCapabilities.internetExplorer());
cap.setBrowserName("internet explorer");
cap.setPlatform(Platform.ANY);
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://51.19.210.111:5555/wd/hub"), cap);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String url = "https://wfn-iat.adp.com/public/index.htm";
driver.get(url);
}
#Test
public void step01_Login() throws Exception {
PP_OBJ_Login.AdminVisiable(driver);
PP_OBJ_Login.Adminlogin(driver).click();-- -> line 86
PP_OBJ_Login.UserName(driver).sendKeys("NorfolkAutoUser6#adp");
PP_OBJ_Login.Submitbtn(driver).click();
PP_OBJ_Login.Password(driver).sendKeys("iatiat01");
Thread.sleep(2000);
PP_OBJ_Login.Submitbtn(driver).click();
Thread.sleep(5000);
}
PP_OBJ_Login.Java
public class PP_OBJ_Login {
private static WebElement element = null;
// WebElement Adminlogin
public static WebElement Adminlogin(WebDriver driver) {-- -- -> Line 38
element = driver.findElement(By.id("adminLogin"));
return element;
}
// WebElement input Field
public static WebElement UserName(WebDriver driver) {
element = driver.findElement(By.id("USER"));
return element;
}
I want this to work using selenium grid and remote web driver. Is there any way to resolve the null pointer issue?
Your Problem is, that you define 'driver' as a class member but you do not instantiate it. So it is null all the time.
public class PP_Main {
private static WebDriver driver;
private static String homeUrl;
//...
And the driver you instantiate inside setUp() is only valid inside the method itself. Although it has exactly the same name it is NOT the 'driver' you defined globally.
#BeforeClass
public static void setUp() throws Exception {
// ...
cap.setPlatform(Platform.ANY);
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://51.19.210.111:5555/wd/hub"), cap);
// ...
}
Instantiate it this way instead
public class PP_Main {
private static RemoteWebDriver driver;
private static String homeUrl;
//...
#BeforeClass
public static void setUp() throws Exception {
// ...
cap.setPlatform(Platform.ANY);
driver = new RemoteWebDriver(new URL("http://51.19.210.111:5555/wd/hub"), cap);
// ...
}
This should work.
I have my listener override like this :
#Override
public void onTestFailure(ITestResult result) {
System.out.println("Test: " + getTestMethodName(result) + " failure");
String methodName=result.getName().toString().trim();
String className = result.getClass().toString().trim();
takeScreenShot(methodName, className);
}
public void takeScreenShot(String methodName, String className) {
driver=className.getDriver(); //it wont work this way :(
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(methodName+".png"));
}
lets say my class is TestClass, and there is method getDriver that returns driver, but:
driver=className.getDriver();
how to pass this className variable ?
i dont want to make separate listeners for each class, and String className is not WebDriver type
any ideas?
public void takeScreenShot(ITestResult itr) {
YourClass currentClass = (YourClass) itr.getInstance();
WebDriver driver = currentClass.getDriver();
// ...
You can work on this, in your class you need to set driver attribute and then you can use this attribute in Listener class for Example
testClass.java
#BeforeClass
public void setDriver(ITestContext context){
WebDriver driver = new FirefoxDriver();
context.setAttribute("WedDeiver", driver);
}
#Test
public void t1(){
// your code
}
Listner.java
WebDriver driver = null;
#Override
public void onTestFailure(ITestResult result) {
ITestContext context = result.getTestContext();
driver = (RemoteWebDriver) context.getAttribute("WebDriver");
// your code
}
You can use above driver from any class now, the only thing is you need to set the driver attribute value in you test class
I want use a common WebDriver instance across all my TestNG tests by extending my test class to use a base class as shown below but it doesn't seem to work :
public class Browser {
private static WebDriver driver = new FirefoxDriver();
public static WebDriver getDriver()
{
return driver;
}
public static void open(String url)
{
driver.get(url);
}
public static void close()
{
driver.close();
}
}
I want to use the WebDriver in my test class as shown below, but I get the error message :
The method getDriver() is undefined for the type GoogleTest:
public class GoogleTest extends Browser
{
#Test
public void GoogleSearch() {
WebElement query = getDriver().findElement(By.name("q"));
// Enter something to search for
query.sendKeys("Selenium");
// Now submit the form
query.submit();
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 5 seconds
WebDriverWait wait = new WebDriverWait(getDriver(), 30);
// wait.Until((d) => { return d.Title.StartsWith("selenium"); });
//Check that the Title is what we are expecting
assertEquals("selenium - Google Search", getDriver().getTitle().toString());
}
}
The problem is that your getDriver method is static.
Solution #1: Make method non-static (this will either need to make the driver variable non-static as well, or use return Browser.getDriver(); )
public WebDriver getDriver() {
return driver;
}
Or, call the getDriver method by using Browser.getDriver
WebElement query = Browser.getDriver().findElement(By.name("q"));
You need to start your driver, one of many solution is to try #Before to add, Junit will autorun it for you.
public class Browser {
private WebDriver driver;
#Before
public void runDriver()
{
driver = new FirefoxDriver();
}
public WebDriver getDriver()
{
return driver;
}
public void open(String url)
{
driver.get(url);
}
public void close()
{
driver.close();
}
}