Baker644
Baker644

Reputation: 13

Passing driver parameter to a method outside main

Im trying to pass a WebDriver object outside my main method, but it isnt being resolved to a variable. I am trying to pass 'driver a' parameter to the method NavigateGoogle. Not a common way to use Selenium but im new and its been eating at me. Code below, Any suggestions?

package day2;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class WebDriverDemo {

    public static void main(String[] args) {
        WebDriver driver  = new ChromeDriver();
        System.setProperty("webdriver.chrome.driver","C:\\Users\\Abu\\Desktop\\Web Drivers\\chromedriver.exe");

    }

    public boolean NavigateGoogle(driver a) {
        //'Driver a' parameter cannot be resolved to a type
        a.get("http://www.google.com");
        return true;

    }

}

Upvotes: 0

Views: 1771

Answers (2)

JNo
JNo

Reputation: 9

As I understand from your question what you looking for is to pass a driver in the method NavigateGoogle(driver a) if that is what you are looking for then the below solution hopefully helps....

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver","C:\\Users\\Abu\\Desktop\\Web Drivers\\chromedriver.exe");
        WebDriver driver  = new ChromeDriver();
    NavigateGoogle(driver);

    }

In the above piece of code the system path is been set and an instance of WebDriver is defined as "driver" The next line of code driver is passed to the function NavigateGoogle(driver)

 public boolean NavigateGoogle(WebDriver driver) {
        a.get("http://www.google.com");
        return true;
    }

The above code is the function that is defined to pass the driver. Further more

WebDriver driver  = new ChromeDriver(); //"driver" is just a instance of WebDriver 
WebDriver a = new ChromeDriver(); //"a" is just a instance of WebDriver 

It's always good to follow a self explainable instance.

Upvotes: 0

CEH
CEH

Reputation: 5909

I think you mean to make the method signature:

public boolean NavigateToGoogle(WebDriver a) { 
    a.get("http://www.google.com");
    return true;
}

WebDriver is a type, but driver is not. You declared WebDriver driver earlier, so the method signature parameter should match.

Also, you are setting your chromedriver.exe path AFTER you try to initialize WebDriver, which is wrong. The statements should be flipped:

public static void main(String[] args) {

    System.setProperty("webdriver.chrome.driver","C:\\Users\\Abu\\Desktop\\Web Drivers\\chromedriver.exe");
    WebDriver driver  = new ChromeDriver();
}

Upvotes: 1

Related Questions