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
Related
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
Environment:
Java + Selenium WebDriver + TestNG
My goal is to launch browser in a new session at #BeforeTest annotation so that all classes under each <test> tag can use the same browser session. I am getting this error when I run TestNG xml suite.
java.lang.NullPointerException: Cannot invoke
"org.openqa.selenium.WebDriver.get(String)" because "this.driver" is
null
Test1
public class Test1 extends BaseTest{
#Test
public void test1() {
driver.get("https://gmail.com");
}
#Test
public void test2()) {
driver.get("https://google.com");
}
}
Test2
public class Test2 extends BaseTest{
#Test
public void test1() {
driver.get("https://aol.com");
}
}
Test3
public class Test3 extends BaseTest{
#Test
public void test1() {
driver.get("https://hotmail.com");
}
}
BaseTest
public class BaseTest{
protected WebDriver driver;
public void initDriver() throws MalformedURLException {
System.setProperty("webdriver.chrome.driver", ".\\src\\main\\resources\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
#BeforeTest
public void beforeTest() {
initDriver();
}
}
TestNG XML Suite
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite" >
<test name="FirstTest">
<classes>
<class name="JavaTestNG.Test1" />
<class name="JavaTestNG.Test2" />
</classes>
</test>
<test name="SecondTest">
<classes>
<class name="JavaTestNG.Test3" />
</classes>
</test>
</suite>
When I run the xml suite, I am getting the following error in Test2 class at this line
driver.get("https://aol.com");
Test1 and Test3 worked just fine but not Test2. As you can see, I have two classes Test1 and Test2 under <test name="FirstTest">. Test1 was able to user the browser session but not Test2. How can Test2 class use the same browser session as Test1?
Stacktrace:
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.get(String)" because "this.driver" is null
at JavaTestNG.Test2.test2_1(Test2.java:15)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:598)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:824)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.testng.TestRunner.privateRun(TestRunner.java:794)
at org.testng.TestRunner.run(TestRunner.java:596)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:377)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)
at org.testng.SuiteRunner.run(SuiteRunner.java:276)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1134)
at org.testng.TestNG.runSuites(TestNG.java:1063)
at org.testng.TestNG.run(TestNG.java:1031)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
I want to run different classes particular method from TestNG but everytime it opens a new window when i include beforeclass in each class so i have now excluded beforeclass from add and logout classes so it can use same browser to run rest methods but its not working
The first class is of login class which is as below
public class LoginWeb {
public WebDriver driver;
WebDriverWait wait;
LoginScreen loginExcel;
#BeforeClass
public void beforeClass (){
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://10.7.1.180/views/index.html#/login");
System.out.println(driver.getTitle());
}
#Test (description = "Valid Credentials!")
public void LoginWithValidWebExcelEmailAndPass() throws IOException, BiffException {
loginExcel= new LoginScreen(driver);
FileInputStream fi = new FileInputStream("D:\\Programs\\New\\Sourcesmartdata.xls");
Workbook w = Workbook.getWorkbook(fi);
Sheet s = w.getSheet(0);
int z = s.getRows();
System.out.println("no of rows------------------------:"+z);
String email = s.getCell(0, 1).getContents();
System.out.println("Email -----------------"+email);
loginExcel.EnterEmail(email);
String password= s.getCell(1, 1).getContents();
System.out.println("Password------------------- "+password);
loginExcel.EnterPassword(password);
loginExcel.ClickToLogin();
wait= new WebDriverWait(driver, 10);
WebElement GetLogo = wait.until(ExpectedConditions.visibilityOf(loginExcel.TopRightMenu));
String str= GetLogo.getText();
System.out.println("Text------------"+str);
Assert.assertEquals(str, "Source Smart");
}
}
The second class is of adding commodities here i have excluded beforeclass as if i include before class it opens a new window and here login script is not written
public class AddCommoditiesWeb{
WebDriver driver;
WebDriverWait wait;
AddCommodities addcommodity;
#Test (description="Add Multiple Commodities!")
public void AddMultipleNewCommodities () throws Exception, Exception{
addcommodity = new AddCommodities(driver);
addcommodity.MenuCommodities(); //click left menu to open manage commodities page
FileInputStream fi = new FileInputStream("D:\\Programs\\New\\Sourcesmartdata.xls");
Workbook w = Workbook.getWorkbook(fi);
Sheet s = w.getSheet(1);
int z=s.getRows();
System.out.println("no of rows------------------------:"+z);
for(int row=1; row <2; row++){
Thread.sleep(5000);
addcommodity.ClickAddCommodities(); // click add commodity button
String commodityname = s.getCell(0, row).getContents();
System.out.println("commodityname -----------------"+commodityname);
//enterdefinecommodityTxtBox.sendKeys(commodityname);
addcommodity.Enterdefinecommodity(commodityname);
String grade= s.getCell(1, row).getContents();
System.out.println("grade------------------- "+grade);
//entergradeTxtBox.sendKeys(grade);
String unit= s.getCell(2, row).getContents();
System.out.println("unit------------------- "+unit);
//enterunitTxtBox.sendKeys(unit);
String minprice= s.getCell(3, row).getContents();
System.out.println("min price------------------- "+minprice);
//enterminpriceTxtBox.sendKeys(minprice);
String maxprice= s.getCell(4, row).getContents();
System.out.println("max price------------------- "+maxprice);
//entermaxpriceTxtBox.sendKeys(maxprice);
addcommodity.EnterAddCommoditiesData(grade,unit,minprice,maxprice);
}
wait=new WebDriverWait(driver,10);
WebElement commodityname= wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div/div[4]/div/section[2]/div[4]/d-expand-collapse[1]/div/div/div[1]/h4/a")));
String commoditynamejustadded= commodityname.getText();
System.out.println("name--------------"+commoditynamejustadded);
assertEquals(commoditynamejustadded, "Rice");
}
}
TestNG code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Login check">
<classes>
<class name="SourceSmartWeb.LoginWeb"/>
<class name = "SourceSmartWeb.AddCommoditiesWeb">
<methods>
<include name="AddMultipleNewCommodities"/>
</methods>
</class>
<class name ="SourceSmartWeb.LogoutWeb"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Logout class:
public class LogoutWeb{
WebDriver driver;
// #BeforeClass
// public void beforeClass (){
// System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
// driver=new ChromeDriver();
// driver.manage().window().maximize();
// driver.get("http://10.7.1.180/views/index.html#/login");
// System.out.println(driver.getTitle());
// super.beforeClass();
//
// }
#Test
public void Logout() throws InterruptedException {
LogoutScreen logout=new LogoutScreen(driver);
logout.ClickToLogout();
}
#AfterClass
public void exit(){
driver.quit();
}
}
What its doing is it opens the browser logins and then do nothing. How can i make it do rest of activities on same browser as if i add before class in second class it opens a new browser and then there i dont have login code. please guide
From what you are stating, it looks like you need to basically have a browser spawned per <test> tag and then share that browser amongst all your test classes. But you cannot make use of the #BeforeTest and #AfterTest annotations because you would need to bring in inheritance into the picture and since these methods are executed only once per <test> you will start seeing NullPointerException.
So the idea is to basically leverage TestNG listeners for this webdriver instantiation and cleanup and have your test classes/methods just query them from within a helper method.
Here's some sample code, that shows all of this in action.
Here's how the listener would look like
package com.rationaleemotions.stackoverflow.qn46239358;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
public class WebdriverSpawner extends TestListenerAdapter {
private static final String WEBDRIVER = "webdriver";
#Override
public void onStart(ITestContext testContext) {
testContext.setAttribute(WEBDRIVER, createDriver());
}
#Override
public void onFinish(ITestContext testContext) {
getWebDriverFromContext(testContext).quit();
}
public static RemoteWebDriver getCurrentWebDriver() {
ITestResult result = Reporter.getCurrentTestResult();
if (result == null) {
throw new IllegalStateException("Please invoke this from within a #Test annotated method");
}
ITestContext context = result.getTestContext();
return getWebDriverFromContext(context);
}
private static RemoteWebDriver getWebDriverFromContext(ITestContext context) {
Object object = context.getAttribute(WEBDRIVER);
if (!(object instanceof RemoteWebDriver)) {
throw new IllegalStateException("Encountered problems in retrieving the webdriver instance");
}
return (RemoteWebDriver) object;
}
private static RemoteWebDriver createDriver() {
return new ChromeDriver();
}
}
Here's how your test classes which now use this above listener can look like (I have intentionally kept it simple and have it open up just a URL, but if you run them you would notice a single browser opening up multiple URLs. So only one browser instance)
package com.rationaleemotions.stackoverflow.qn46239358;
import org.testng.annotations.Test;
public class LoginWeb {
#Test(description = "Valid Credentials!")
public void LoginWithValidWebExcelEmailAndPass() {
System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.google.com"));
}
}
package com.rationaleemotions.stackoverflow.qn46239358;
import org.testng.annotations.Test;
public class LogoutWeb {
#Test
public void Logout() throws InterruptedException {
System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.facebook.com"));
}
}
package com.rationaleemotions.stackoverflow.qn46239358;
import org.testng.annotations.Test;
public class AddCommoditiesWeb {
#Test(description = "Add Multiple Commodities!")
public void AddMultipleNewCommodities() {
System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.yahoo.com"));
}
#Test
public void anotherTestMethod() {
System.err.println("Page title : " + PageLoader.loadAndGetTitle("http://www.ndtv.com"));
}
}
The PageLoader utility class looks like this
package com.rationaleemotions.stackoverflow.qn46239358;
import org.openqa.selenium.remote.RemoteWebDriver;
public final class PageLoader {
private PageLoader() {
//Utility class defeat instantiation
}
public static String loadAndGetTitle(String url) {
RemoteWebDriver driver = WebdriverSpawner.getCurrentWebDriver();
driver.get(url);
return driver.getTitle();
}
}
Here's how the suite xml looks like :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="46216357_Suite" verbose="2">
<listeners>
<listener class-name="com.rationaleemotions.stackoverflow.qn46239358.WebdriverSpawner"/>
</listeners>
<test name="Login_check">
<classes>
<class name="com.rationaleemotions.stackoverflow.qn46239358.LoginWeb"/>
<class name="com.rationaleemotions.stackoverflow.qn46239358.AddCommoditiesWeb">
<methods>
<include name="AddMultipleNewCommodities"/>
</methods>
</class>
<class name="com.rationaleemotions.stackoverflow.qn46239358.LogoutWeb"/>
</classes>
</test>
</suite>
So here none of your #Test classes invoke driver.quit() explicitly. The webdriver cleanup is managed by the listener.
This model is going to work only when you want to run multiple tests on the same browser.
The flip side of this would be that, you can NEVER run your #Test methods in parallel, because now all your tests are sharing the same browser.
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.
I have a driver object initialized in class sample.I want to pass the driver object to other classes also but i get a null pointer exception. My code is
sample class
public class sample {
WebDriver driver ;
#Test(priority=1)
public void openbrowser(){
System.setProperty("webdriver.chrome.driver",
"/home/ss4u/Desktop/Vignesh/jars/chromedriver");
driver = new ChromeDriver();
driver.get("http://www.google.com");
System.out.println(driver instanceof WebDriver);
}
#Test(priority=2)
public void maximize(){
driver.manage().window().maximize();
}
#Test(priority=3)
public void transfer_instance(){
sampleone obj=new sampleone(driver);
}
}
sampleclassone
public class sampleone {
WebDriver driver;
public sampleone(WebDriver driver){
this.driver=driver;
System.out.println(driver instanceof WebDriver);
System.out.println(this.driver instanceof WebDriver);
System.out.println("constructor2");
}
public sampleone(){
System.out.println("Default constructor called");
}
#Test(priority=1)
public void gettitle(){
System.out.println(this.driver instanceof WebDriver);
System.out.println(driver instanceof WebDriver);
String title=this.driver.getTitle();
System.out.println(this.driver instanceof WebDriver);
System.out.println(title);
Assert.assertEquals(title, "Google");
}
#Test(priority=2)
public void navigate(){
this.driver.get("https:in.yahoo.com");
}
}
Testng xml file
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="TestNG" verbose="1" >
<test name="sample test">
<classes>
<class name="testsample.sample" />
</classes>
</test>
<test name="sample testone">
<classes>
<class name="testsample.sampleone" />
</classes>
</test>
</suite>
This issue occurs as iam calling the class not using the object created but using the testng.xml file is there any possible way to create a new java instance(common for all classes) or use the existing instance in all classes
I found a solution myself...When i read about the testng in detail i found that testng xml file calls the default constructor of all classes specified in the xml file.so even if we pass the object to another class we cannot perform the action through the object so null pointer exception occurs....i found two solutions first one is to use a pagefactory and second one 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", "/home/vicky/Documents/Jars/chromedriver");
driver=new ChromeDriver();
}else if(browser.equals("Firefox")){
driver=new FirefoxDriver();
}
return driver;
}
}
It is very easy to use with extends keyword same as Java. Just you need to create common webdriver class where you will open required browser and application url with the help of TestNG annotations as below code.
WebDriver Common Class:
public class Seleniumlinktext {
public WebDriver driver;
String baseurl = "http://www.google.co.in";
#BeforeTest
public void openBrowser(){
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
}
Another Class:
public class WebDriverTest extends Seleniumlinktext {
#Test(priority=1)
public void linkText(){
//images hyperlink
driver.findElement(By.linkText("Images")).click();
System.out.println("Click on Images hyperlink");
}
Like this way you can pass webdriver instance to all other clases. I found the solution from this site.
Here I have used #BeforeTest annotation because my application url and browser should be open only once before starting my Test cases execution with #Test annotation.