Selenium Grid running tests in parallel - selenium-webdriver

Currently, I have a Selenium grid setup, with 1 local hub and 2 local nodes. The hub is capable of distributing the tests to run in parallel and distribute it over to the nodes. I am running the tests in parallel.
The following is the base test
public abstract class BaseTest
{
String testFolder;
String testName;
protected String envName;
protected Configuration config;
protected String host;
protected RemoteWebDriver driver;
protected String proxy;
protected SomeData someData;
protected SomeController someController;
public BaseTest() {
}
public BaseTest( String testFolder, String testName)
{
this.testFolder = testFolder;
this.testName = testName;
this.envName = System.getProperty("config");
this.proxy = System.getProperty("proxy");
config = this.envName;
}
#BeforeMethod
public void startTest(Method testMethod) {
LOG.info("Starting test: " + testMethod.getName());
try {
this.someData = new SomeData();
this.driver = WebDriverSetup.getDriver();
this.someController = new someController(this.driver, this.someData);
driver.navigate().to("https://" + this.host);
} catch (MalformedURLException e) {
System.out.println("MalformedURLException");
}
}
#AfterMethod
public void closeWindow() {
driver.close();
driver.quit();
}
}
The following is the class to get the RemoteWebDriver:
public class WebDriverSetup {
public static RemoteWebDriver getDriver() throws MalformedURLException{
String SELENIUM_HUB_URL = "http://localhost:4444/wd/hub";
ThreadLocal<RemoteWebDriver> remoteWebDriver = null;
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
String proxy = System.getProperty("proxy");
if (proxy != null && !proxy.isEmpty()) {
System.out.println("Using proxy: " + proxy);
capabilities.setCapability(CapabilityType.PROXY, proxy);
}
try {
remoteWebDriver = new ThreadLocal<RemoteWebDriver>();
remoteWebDriver.set(new RemoteWebDriver(new URL(SELENIUM_HUB_URL),
capabilities));
} catch (MalformedURLException e) {
System.out.println("Tackle Issue with RemoteDriverSetup");
}
remoteWebDriver.get().manage().window()
.setSize(new Dimension(2880, 1524));
remoteWebDriver.get().manage().timeouts()
.pageLoadTimeout(10, TimeUnit.SECONDS);
remoteWebDriver.get().manage().timeouts()
.implicitlyWait(10, TimeUnit.SECONDS);
return remoteWebDriver.get();
}
}
My test suite is like :
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Multiple Tests Suite" verbose="1" parallel="methods">
<test name="Test1">
<classes>
<class name="com.itesteverything.qa.Tests"></class>
</classes>
</test>
</suite>
Tests are like :
public class Tests extends BaseTest {
#Parameters({"testName", "env" })
public Tests( #Optional String testName, #Optional String env ) {
super( null, testName, null, env );
}
#BeforeMethod
public void setup() throws Exception {
//setSomeData
}
public void test1() throws Exception {
use driver from super
use someData from super
use someController is using the driver from super
}
public void test2() throws Exception {
use driver from super
use someData from super
use someController is using the driver from super
}
While running these tests, I get the following errors
Build info: version: '2.44.0', revision: '76d78cf323ce037c5f92db6c1bba601c2ac43ad8', time: '2014-10-23 13:11:40'
Driver info: driver.version: RemoteWebDriver
org.openqa.selenium.remote.SessionNotFoundException: Session ID is null. Using WebDriver after calling quit()?
Build info: version: '2.44.0', revision: '76d78cf323ce037c5f92db6c1bba601c2ac43ad8', time: '2014-10-23 13:11:40'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:572)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:352)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:393)
at org.openqa.selenium.By$ById.findElement(By.java:214)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:59)
at com.sun.proxy.$Proxy25.sendKeys(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:673)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:842)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1166)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
TEST FAILED: test2
FAILED REASON: Session ID is null. Using WebDriver after calling quit()?
Is it something anyone aware of?
Thanks in advance!

Do not set driver in the base class, do not have driver property at all. The same instance is being overridden by different threadlocal drivers.
Any time you want to run your test, refer to WebDriverSetup.getDriver() in your test method itself and in your after/before methods.

#AfterMethod
Is running after each method.
And U run's only one setup. So after first method U close and it is closed as shows stack trace.

Related

TestNG - Test methods are not executing even with ThreadLocal Webdriver

I have used implementation of ThreadLocal for Webdriver to run test methods in parallel from single Test class. I used BeforeMethod for LaunchingApplication and AfterMethod for teardown. Though my 6 different methods I have in Test class have different Thread IDs and 6 browser windows are opened, only one method is navigated to url and executing the method and close the browser window. Other 5 browser windows are just opened and no further actions are performed. I assume the only method that is exectued is having first thread ID.
My project in Github:
https://github.com/venkatakarteek/Practice
Please help to see my code in
BaseClass in src/test/java/com/Assignment/TestComponents
TestCases in src/test/java/com/Assignment/TestCases/TestCases
testng.xml - used to run the test methods in parallel
BaseClass
public class BaseClass {
public WebDriver driver;
protected static ThreadLocal<WebDriver> threadSafeDriver = new ThreadLocal<>();
public HomePage homePage;
public WebDriver browsersetup() throws IOException {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream(
System.getProperty("user.dir") + "\\src\\main\\resource\\GlobalData.Properties");
prop.load(fis);
String browserName = System.getProperty("browser") != null ? System.getProperty("browser")
: prop.getProperty("browser");
if (browserName.contains("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
}
else if (browserName.contains("edge")) {
WebDriverManager.edgedriver().setup();
driver = new EdgeDriver();
} else if (browserName.contains("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.manage().window().maximize();
return driver;
}
#BeforeMethod(alwaysRun = true)
public HomePage LaunchApplication() throws IOException {
driver = browsersetup();
threadSafeDriver.set(driver);
System.out.println("Before Method Thread ID: " + Thread.currentThread().getId());
driver = threadSafeDriver.get();
homePage = new HomePage(driver);
homePage.goTo();
return homePage;
}
#AfterMethod(alwaysRun = true)
public void tearDown() throws IOException {
driver.close();
System.out.println("After Method Thread ID: " + Thread.currentThread().getId());
threadSafeDriver.remove();
}
}
TestCases class
public class TestCases extends BaseClass {
#Test
public void Test1() {
System.out.println("Test1 Method Thread ID: " + Thread.currentThread().getId());
homePage.checkIfElementIsDisplayed(homePage.emailElement);
homePage.checkIfElementIsDisplayed(homePage.passwordElement);
homePage.checkIfElementIsDisplayed(homePage.signInElement);
homePage.emailElement.sendKeys("karteek#gmail.com");
homePage.passwordElement.sendKeys("******");
}
#Test
public void Test2() {
System.out.println("Test2 Method Thread ID: " + Thread.currentThread().getId());
homePage.checkValuesInListGroup();
homePage.checkSecondListItem();
homePage.checkSecondListItemBadgeValue();
}
#Test
public void Test3() throws InterruptedException {
System.out.println("Test3 Method Thread ID: " + Thread.currentThread().getId());
homePage.ScrolltotheElement(homePage.dropDownOption);
homePage.checkDefaultSelectedValue();
homePage.selectOption3();
}
#Test
public void Test4() {
System.out.println("Test4 Method Thread ID: " + Thread.currentThread().getId());
homePage.ScrolltotheElement(homePage.enabledButtonElement);
homePage.checkIfFirstButtonisEnabled();
homePage.checkIfButtonisDisabled(homePage.disabledButtonElement);
}
#Test
public void Test5() {
System.out.println("Test5 Method Thread ID: " + Thread.currentThread().getId());
homePage.ScrolltotheElement(homePage.test5Div);
homePage.ExplicitWait(homePage.test5Button);
homePage.clickOnButton();
homePage.checkIfButtonisDisabled(homePage.test5Button);
}
#Test
public void Test6() throws IOException {
System.out.println("Test6 Method Thread ID: " + Thread.currentThread().getId());
homePage.ScrolltotheElement(homePage.test6Div);
String cellValue = homePage.findValueOfCell(driver, 2, 2);
System.out.println(cellValue);
}
}
XML used to run test methods in parallel
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test thread-count="6" name="Test" parallel="methods">
<classes>
<class name="com.Assignment.TestCases.TestCases" />
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
I tried this ThreadLocal implementation by seeing the post from Linkedin
https://www.linkedin.com/pulse/selenium-parallel-testing-using-java-threadlocal-testng-shargo/
but getting parallel execution is not working for my code to run methods parallely

Getting InstantiationException when creating factory for a page using appium

I am running a test case using pagefactory method and have created an appium driver. I'm trying to initialising a page using pagefactory class like this:
The test class:
public class VerifyValidLogin {
#Test
public void CheckValidUser() throws MalformedURLException {
AppiumDriver driver = DeviceFactory.CreateDriver();
login login_page = PageFactory.initElements(driver, login.class);
}
}
DeviceFactory class:
public class DeviceFactory {
public static AppiumDriver<MobileElement> driver;
public static AppiumDriver CreateDriver() throws MalformedURLException {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability( capabilityName: 'deviceName', value: 'Something');
...
URL url = new URL("http://127.0.0.1:4723/wd/hub");
driver = new AppiumDriver<MobileElement>(url,cap);
System.out.print("Application started");
return driver;
}
}
Login class has element locators:
public class login {
AppiumDriver driver;
public login(AppiumDriver ldriver)
{
this.driver=ldriver;
}
#FindBy(how = How.XPATH,using ="xpath");
MobileElement SignInButton;
}
But i'm not sure where i am doing wrong.
The error is
java.lang.RuntimeException: java.lang.InstantiationException: com.Demo.pages.login
at org.openqa.selenium.support.PageFactory.instantiatePage(PageFactory.java:134)
at org.openqa.selenium.support.PageFactory.initElements(PageFactory.java:64)
at com.Demo.Testcases.VerifyValidLogin.CheckValidUser(VerifyValidLogin.java:18)
...
I am new to the automation testing so i'm not able to properly understand the error. Let me know if you need more details.
Initialise elements in constructor
public login(AppiumDriver ldriver)
{
this.driver=ldriver;
PageFactory.initElements(ldriver,this);
}

Getting NullPointeException while running the Selenium test script

I am getting the NullPointerException after executing the below testng test script. After launching the URL when it comes inside the test script method then, it is throwing the exception. Can you please help me out in this.
(Object Repo) LakesAndMountainsHomePage.java :-
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.actitime.genericlib.WebDriverCommonLib;
public class LakesAndMountainsHomePage extends WebDriverCommonLib{
WebDriver driver;
public LakesAndMountainsHomePage(WebDriver driver)
{
this.driver = driver;
PageFactory.initElements(driver, this);
}
#FindBy(xpath= "//*[#id='the-main-menu']//*[contains(text() , 'LAKES &
MOUNTAINS')]")
WebElement LandM;
public WebElement LandMHeader()
{
System.out.println("came inside the method");
//LandM.isDisplayed();
return LandM;
}
}
BaseTest.java:-
public abstract class BaseTest {
ExcelLib eLib;
WebDriverCommonLib wLib;
WebDriver driver;
HomePage homepage;
#BeforeClass
public void baseBeforeClass()
{
eLib = new ExcelLib();
wLib = new WebDriverCommonLib();
driver=Driver.getBrowser();
driver.manage().window().maximize();
System.out.println("Browser is launched");
}
#BeforeMethod
public void launchURL()
{
wLib.homePage();
//loginPage.loginToAPP();
System.out.println("Navigated to the URL");
}
}
Testscript:-
public class LakesAndMountainsHomePageTest extends BaseTest{
LakesAndMountainsHomePage lm = new LakesAndMountainsHomePage(this.driver);
//TC TC131409 [New Lakes & Mountains Tab] : Verify New Lakes & Mountains
Tab is displayed in header.
#Test(priority=0)
public void lakesAndMountainsHeader()
{
boolean a= lm.LandMHeader().isDisplayed(); //getting exception here
if(a==true)
{
System.out.println("Lakes And Mountains tab is present in the HomePage");
}
else
{
System.out.println("Lakes And Mountains tab is not present in the
HomePage");
}
lm.LandMHeader().click();
System.out.println("It has clicked the tab");
}
}
And below is the exception stack trace:-
below is the exception stacktrace:-
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.$Proxy9.isDisplayed(Unknown Source)
at com.acttime.usertest.LakesAndMountainsHomePageTest.lakesAndMountainsHeader(LakesAndMountainsHomePageTest.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:669)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:877)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1201)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:776)
at org.testng.TestRunner.run(TestRunner.java:634)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:425)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:420)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:385)
at org.testng.SuiteRunner.run(SuiteRunner.java:334)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1318)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1243)
at org.testng.TestNG.runSuites(TestNG.java:1161)
at org.testng.TestNG.run(TestNG.java:1129)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
I am getting the NullPointerException after executing the below testng test script. After launching the URL when it comes inside the test script method then, it is throwing the exception. Can you please help me out in this.
This instantiation is illegal.
LakesAndMountainsHomePage lm = new LakesAndMountainsHomePage(this.driver);
It is the root cause of Null pointer exception.
Move this statement to BaseTest class, create a class field and instantiate inside #BeforeClass method . Also, remove this operator.
Well i'am unable to see the implementation of a driver class specifying the type of driver(firefox,chrome,IE) being initialized.

Quit() is not working in selenium grid 3.4.0 (ThreadLocal)

I am using selenium grid and selenium 3.4.0 version. I am getting error for the tearDown() function (Browser closing but error at the function), I tried #After, before, suite, class etc annotation at tearDown() function but not working. Please suggest what is my mistake and how to resolve.
Base class:
public class TestBase {
//public ThreadLocal<RemoteWebDriver> driver;
public ThreadLocal<RemoteWebDriver> driver = new ThreadLocal<RemoteWebDriver>();
//Do the test setup
#BeforeMethod
#Parameters(value="browser")
public void setupTest (String browser) throws MalformedURLException {
//Assign driver to a ThreadLocal
//driver = new ThreadLocal<>();
DesiredCapabilities capabilities = new DesiredCapabilities();
if (browser.equals("chrome")) {
capabilities.setCapability("browserName", browser);
driver.set(new RemoteWebDriver(new URL("http://123.123.0.50:4444/wd/hub"), capabilities));
} else if(browser.equals("internet explorer")){
capabilities.setCapability("browserName", browser);
driver.set(new RemoteWebDriver(new URL("http://123.123.0.50:4444/wd/hub"), capabilities));
capabilities.setCapability(InternetExplorerDriver.IE_ENSURE_CLEAN_SESSION, true);
}
else if(browser.equals("firefox")){
capabilities.setCapability("browserName", browser);
driver.set(new RemoteWebDriver(new URL("http://123.123.0.50:4444/wd/hub"), capabilities));
}
}
public WebDriver getDriver() {
return driver.get();
}
#AfterMethod
public void tearDown() throws Exception {
//getDriver().close();
getDriver().quit();
}
}
First Class:
public class FirstTest extends TestBase {
#Test
public void firstTest() throws Exception {
System.out.println("First Test Started!");
getDriver().navigate().to("http://www.facebook.com");
System.out.println("First Test's Page title is: " + getDriver().getTitle());
System.out.println("First Test Ended!");
}
#Test
public void firstTests() throws Exception {
System.out.println("First of Second Test Started!");
getDriver().navigate().to("http://www.facebook.com");
System.out.println("First Test's Page title is: " + getDriver().getTitle());
System.out.println("First of Second Test Ended!");
}
}
TestNG.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests" thread-count="2">
<test name="FFTest">
<parameter name="browser" value="firefox" />
<classes>
<class name="parallelGrid.SecondTest" />
</classes>
</test>
</suite>
Error message:
org.openqa.selenium.WebDriverException: quit
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
I do not know your Node url you using. Try this link and setup hub, node then try your code, if worked then you have an issue with node url else let us know the node url you using.
Link for your solution

Nullpointer Exception in webdriver, driver is null

I am a newbie in selenium java and trying to run test case by calling methods from another class in a framework. Methods are defined in a different class. The issue is that for first instance, the driver is found (Firefox driver) but when a method from another class is called, the driver is null.
Below is the code snippet:
public class ActionDriver {
WebDriver driver;
public ActionDriver(WebDriver driver){
this.driver = driver;
}
public void type(By loc, String value) {
driver.findElement(loc).sendKeys(value);
}
}
NPE comes for the above line of code for driver for second instance when method is called from the WebAction class. driver.findElement(loc).sendKeys(value);
Second class is :
public class WebActions {
WebDriver driver;
ActionDriver ad = new ActionDriver(driver);
SizeChartTemplate sct = new SizeChartTemplate();
public void TypeTemplateName(){
ad.type(jsct.Template_Name, "Men's Vest");
}
}
NPE is for the above line of code at ad.
Test Case:
public class LoginToJcilory extends OpenAndCloseBrowser {
#Test
public void logintojcilory() throws BiffException, IOException, InterruptedException{
WebActions wa = new WebActions();
System.out.println("Entered login to jcilory block");
ActionDriver actdrvr = new ActionDriver(driver);
JciloryLoginPage jclp = new JciloryLoginPage();
JcilorySizeChartTemplate jsct = new JcilorySizeChartTemplate();
String username = actdrvr.readExcel(0, 1);
String password = actdrvr.readExcel(1, 1);
System.out.println(username);
System.out.println(password);
actdrvr.type(jclp.Username, username);
actdrvr.type(jclp.Password, password);
actdrvr.click(jclp.LoginButton);
Thread.sleep(2000);
driver.get("http://qacilory.dewsolutions.in/JCilory/createSizeChartTemplate.jc");
wa.TypeTemplateName();
}
NPE comes for wa element in the above code.
Below is the error:
FAILED: logintojcilory
java.lang.NullPointerException
at Config.ActionDriver.type(ActionDriver.java:40)
at Config.WebActions.TypeTemplateName(WebActions.java:17)
at Test.LoginToJcilory.logintojcilory(LoginToJcilory.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.access$000(SuiteRunner.java:37)
at org.testng.SuiteRunner$SuiteWorker.run(SuiteRunner.java:368)
at org.testng.internal.thread.ThreadUtil$2.call(ThreadUtil.java:64)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
===============================================
Test run on FIREFOX
Tests run: 1, Failures: 1, Skips: 0
===============================================
OpenAndCloseBrowser:
public class OpenAndCloseBrowser {
protected WebDriver driver;
#Parameters({"browser","baseURL"})
#BeforeClass
public void openBrowser(String browser,String baseURL){
if(browser.equalsIgnoreCase("firefox")){
driver=new FirefoxDriver();
}
else if(browser.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\driver\\chromedriver.exe");
driver=new ChromeDriver();
}
else if(browser.equalsIgnoreCase("ie")){
System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+"\\driver\\IEDriverServer.exe");
DesiredCapabilities caps=new DesiredCapabilities();
caps.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver=new InternetExplorerDriver(caps);
}
else{
driver=new FirefoxDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get(baseURL);
}
#AfterClass
public void closeBrowser(){
//driver.quit();
}
}
I guess there is an issue with the way i am defining the driver in these classes. Any help is resolving the issue is appreciated.
Your driver is null in ActionDriver.type() because it was null when it was passed into the constructor from WebActions. OpenAndCloseBrowser is creating a WebDriver instance, but assigning to a DIFFERENT (local) driver variable. You should learn more about variable scoping in Java...this isn't a Selenium/Webdriver issue.
You probably don't need an answer anymore, but this issue has quite the views, so just for completeness.
I usually have a global driver variable in my test class and I instantiate it like this, so it's available for every test.
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
Just add this to your test class (adapt driver path) and the driver is instantiated before the test.

Resources