public class DriverFactory {
public WebDriver driver;
public static ThreadLocal<WebDriver> tlDriver = new ThreadLocal<>();
/**
* This method is used to initialize the threadlocal driver on the basis of given
* browser
*
* @param browser
* @return this will return tldriver.
*/
public WebDriver init_driver(String browser) {
System.out.println("browser value is: " + browser);
if (browser.equals("chrome")) {
WebDriverManager.chromedriver().setup();
tlDriver.set(new ChromeDriver());
} else if (browser.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
tlDriver.set(new FirefoxDriver());
} else if (browser.equals("safari")) {
tlDriver.set(new SafariDriver());
} else {
System.out.println("Please pass the correct browser value: " + browser);
}
getDriver().manage().deleteAllCookies();
getDriver().manage().window().maximize();
return getDriver();
}
/**
* this is used to get the driver with ThreadLocal
*
* @return
*/
public static synchronized WebDriver getDriver() {
return tlDriver.get();
}
}
2 Answers
Check your property file, you may have not set the below key-value
#Browser config:
browser = chrome
Property file location:
You may have the below code in your ApplicationHooks
class. browserName
variable seems to be null. Hence you are getting NPE when you call the method driverFactory.init_driver
public void launchBrowser() {
String browserName = prop.getProperty("browser");
driverFactory = new DriverFactory();
driver = driverFactory.init_driver(browserName);
driver.get(prop.getProperty("appURL"));
}
Note- I happened to have the same framework(source code), hence am very particularly specifying the other parts of the code which you have not even mentioned in your question.
We generally tend to encounter this issue when we used to test web applications during our outsourced software testing project.
I have one approach to solving the problem you are facing. Sharing the code snippet in below example:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ChromeDriverThreadLocal {
private static final String CHROME_DRIVER_PATH = "/path/to/chromedriver";
private static final ThreadLocal<WebDriver> driver = new ThreadLocal<>();
public static WebDriver getDriver() {
if (driver.get() == null) {
System.setProperty("webdriver.chrome.driver", CHROME_DRIVER_PATH);
driver.set(new ChromeDriver());
}
return driver.get();
}
}
In this example, each thread will have its own instance of ChromeDriver
that is accessible through the getDriver()
method. This ensures that the driver instance is thread-safe and can be used by multiple threads without conflicting with each other. Similarly, you can also add other browser capabilities as well.
NullPointerException
stands for? Have you looked at your stacktrace? See this answer to see how to read stacktraces and understand exceptions: sqa.stackexchange.com/a/51649/1933