Java + Selenium Session ID is null. Using WebDriver after calling quit() - java

I am having issues trying to run Selenium Web driver in a specific way, I've have setup TestNG + Selenium Web driver in my framework, the thing that I would like to accomplish is to run two suites that I've set up in the TestNG.xml files as bellow:
TestNG.xml
<suite>
<suite-files>
<suite-file path="src/testNG/suites/UserSignsOn.xml" />
<suite-file path="src/testNG/suites/PreSetup.xml" />
</suite-files>
</suite>
PreSetup.xml
<suite name="Pre Setup">
<test name="pre setup suite">
<classes>
<class name="Tests.PreSetup" />
</classes>
</test>
</suite>
UserSignsOn.xml
<suite name="User Signs On">
<test name="Get the Web Application">
<classes>
<class name="Tests.LoginPageTest" />
</classes>
</test>
</suite>
My test files look like this:
LoginPageTest.class
public class LoginPageTest extends BaseTest {
#Test
#Description("Login to the web application")
public void signInTheWebApplicationLocalHost(){ // some steps here }
}
PreSetup.class
public class PreSetup extends BaseTest {
#Test
#Description("Pre setup")
public void preSetupSteps(){ // some steps here }
}
As you can see my Test files extends a class, which is the following:
BaseTest.class
public class BaseTest {
protected EnvironmentManager environmentManager;
#BeforeTest
public void testSetup() {
environmentManager = EnvironmentManager.getInstance();
if(environmentManager.getDriver() == null){
// Here I am set up the driver!!!
environmentManager.initWebdriver();
environmentManager.startWebApplication();
}
}
#BeforeMethod
public void testName(ITestResult result){ // perform some actions }
#AfterMethod
public void status(ITestResult result){ // perform some actions }
#AfterTest // Here I am shutting down the driver
public void tearDown() { environmentManager.shutdownDriver(); }
}
The BaseTest.class calls to the EnvironmentManager.class which is a singleton class
It has the bellow code:
public class EnvironmentManager {
private static EnvironmentManager instance = null;
private WebDriver driver = null;
private String url = "www.google.com";
private EnvironmentManager(){}
// Public Methods
public void initWebdriver() {
if(driver == null){ driver = new ChromeDriver(); }
}
public void startWebApplication(){ driver.get(url); }
// Singleton method
public static EnvironmentManager getInstance() {
if (instance == null) instance = new EnvironmentManager();
return instance;
}
public void shutdownDriver(){
driver.quit();
driver = null;
}
public WebDriver getDriver(){ return driver; }
}
The issue resides after running the second test "PreSetup", in the console I got the error:
Session ID is null. Using WebDriver after calling quit()?
I notice that in the first test the driver session is:
ChromeDriver: chrome on MAC (0ff799fbfd14fc275b3b45c414765b15)
And in the second test is a different one:
ChromeDriver: chrome on MAC (09c6c47344756fe2979ee8a84094b1e3)
Any help is welcome :)

for all interested the solution is to rename the following testNG annotations:
#BeforeTest
#AfterTest
to
#BeforeSuite
#AfterSuite

Related

Executing Selenium tests one after the other without re launching the browser through testng

I have two testcases that has to be executed
1.Login to an App
2.Perform some operations
Below is the design of my code:
BaseTest.java
public abstract class BaseTest {
public WebDriver driver;
#BeforeSuite
public void openApplication() {
System.setProperty(chrome_key,chrome_value);
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.get(url);
}
}
LoginPage.java
public class LoginPage extends BasePage{
#FindBy (xpath = "//input[#id='username']")
WebElement userName;
#FindBy (xpath = "//input[#id='password']")
WebElement password;
public LoginPage(WebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
}
public void loginToApp(String username, String pwd) {
}
}
Account.java:
public class NewAccount extends BasePage{
#FindBy(xpath = "//span[text()='Accounts']/../..")
WebElement accountsTab;
public NewAccount(WebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
}
public void createNewAccount() {
}
}
LoginToApp.java:
public class LoginToApp extends BaseTest {
#Test
public void a_verifyLogin() throws IOException {
LoginPage hp = new LoginPage(driver);
hp.loginToApp(username, password);
}
}
CreateAccount.java:
public class CreateAccount extends BaseTest {
#Test
public void b_createAccountRecord() {
NewAccount na = new NewAccount(driver);
na.createNewAccount();
}
}
testng.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class name="com.testcases.LoginToApp"/>
<class name="com.testcases.CreateAccount"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
With this framework structure, When I execute the testng.xml file, the first test in LoginToApp executes as expected. And When the control comes to the test in CreateAccount, the driver becomes Null and hence failing the execution of the 2nd Test.
Expected Flow:
1.Initialise Browser
2.Launch the url
3.Execute the #Test method of LoginToApp.java
4.Execute the #Test method of CreateAccount.java
Is it possible to achieve the above flow without making the WebDriver as static? If yes, please explain.
1.Initialise Browser (set this under before method)
2.Launch the url (give priority =0)
3.Execute the #Test method of LoginToApp.java (give priority =1)
4.Execute the #Test method of CreateAccount.java( give depends on method )
depends on method only execute if your loginapp test successfully run

How to log Test Suite name before suite

I want to log name of the test suite before running it. I succeed on logging method names but couldn't figure out how I can do the same thing with suites. My code:
EDIT: I found the solution. Here is the code for those who need it.
public class TestCase {
private Logger logger = LogManager.getLogger(this.getClass());
protected static WebDriver driver;
private String url = PropertyManager.getUrl();
private String browser = PropertyManager.getBrowser();
#BeforeSuite
protected void setUp(ITestContext tes) {
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
System.setProperty("webdriver.chrome.logfile", "chromedriver.log");
System.setProperty("webdriver.chrome.verboseLogging", "true");
driver = new ChromeDriver();
driver.get(url);
driver.manage().window().maximize();
logger.info("Starting up {} driver.", browser);
logger.info(tes.getSuite().getName());
}
This can be done by adding Listener in the project. Use IInvokedMethodListener to perform activities before invocation of intended method.
Steps:
Create a class lets say ListenerClass and implement IInvokedMethodListener interface in it.
public class ListenerClass implements IInvokedMethodListener
Add all unimplemented method and add below code in beforeInvocation method :
#SuppressWarnings("deprecation")
#Override
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
try {
if (method.getTestMethod().getMethod().getAnnotation(org.testng.annotations.BeforeSuite.class)
.toString() != null) {
System.out.println("Before suite annoted method name - " + method.getTestMethod().getMethodName());
System.out.println("Test suite name - " + testResult.getTestContext().getSuite().getName());
}
} catch (Exception e) {
}
}
Add the listener class in your testng.xml file
<listeners>
<listener class-name="ListenerClass"></listener>
</listeners>
<test name="Test_Name">
<classes>
<class name="Test_Class_Name" />
</classes>
</test> <!-- Test -->
Run testng.xml as TestNGSuite you will get the expected result. Let me know if any thing is there

How to use the same browser window in multiple classes using TestNG Selenium webdriver in java?

I am trying to automate a webpage which has a login and post login has many menu item. I would like to automate it in such a way that it logs into the webpage only once and then use the different menu items. Each new menu item automation is created in a different class.
package pack1;
public class Init {
public WebDriver driver;
ChromeOptions options;
#BeforeSuite
public void beforeSuite() throws AWTException, InterruptedException, IOException {
//Setting Chrome Driver and disabling the save password option
System.setProperty(“webdriver.chrome.driver”,”C:\\Users\\user\\Desktop\\Demo\\chromedriver.exe”);
options = new ChromeOptions();
Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put(“credentials_enable_service”, false);
prefs.put(“profile.password_manager_enabled”, false);
options.setExperimentalOption(“prefs”, prefs);
driver=new ChromeDriver(options);
//Opening the URL
driver.get(“myURL”);
driver.manage().window().maximize();
//Login to the portal
driver.findElement(By.xpath(“.//*[#id=’content-wrapper’]/div/div/div/div/div/div/div/form/div/div[1]/input”)).sendKeys(username);
driver.findElement(By.xpath(“.//*[#id=’content-wrapper’]/div/div/div/div/div/div/div/form/div/div[2]/input”)).sendKeys(password);
driver.findElement(By.xpath(“.//*[#id=’content-wrapper’]/div/div/div/div/div/div/div/form/div/div[3]/button”)).click();
}
#AfterSuite
public void afterSuite() {
//Closing the driver
// driver.close();
}
}
Class A
package pack1;
public class ClassA extends Init{
#Test (priority=0, enabled = true)
public void Setup() throws InterruptedException{
//Traversing the menu to reach contract grower setup
Thread.sleep(5000);
driver.findElement(By.linkText(“Menu1”)).click();
driver.findElement(By.linkText(“SubMenu1”)).click();
}
}
Class B
package pack1;
public class ClassBextends Init{
#Test (priority=0, enabled = true)
public void Setup() throws InterruptedException{
//Traversing the menu to reach contract grower setup
Thread.sleep(5000);
driver.findElement(By.linkText(“Menu2”)).click();
driver.findElement(By.linkText(“SubMenu2”)).click();
}
}
testing.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd”>
<suite name=”Suite”>
<test name=”Test”>
<classes>
<class name=”pack1.ClassA”/>
<class name=”pack1.ClassB”/>
<class name=”pack1.Init”/>
</classes>
</test> <!– Test –>
</suite> <!– Suite –>
You should make the following changes:
Configure WebDriver in the Init Class to be static
Don't inherit the Init class in the Test Classes
To use driver in test classes, access it as Init.getDriver();
Base Class
public class Init {
private static WebDriver driver;
public static WebDriver getDriver() {
return driver;
}
#BeforeSuite
public void beforeSuite() {
System.out.println("BS");
System.setProperty("webdriver.chrome.driver", "");
driver = new ChromeDriver();
driver.get("https://www.google.com");
}
#AfterSuite
public void afterSuite() {
System.out.println("AS");
driver.quit();
}
}
Class A
public class ClassA {
#Test(priority = 0, enabled = true)
public void classATest() throws InterruptedException {
System.out.println("classATest");
Init.getDriver().findElement(By.name("q")).sendKeys("Class 1");
}
}
Class B
public class ClassB {
#Test(priority = 0, enabled = true)
public void class2Test() throws InterruptedException {
System.out.println("classBTest");
Init.getDriver().findElement(By.name("q")).sendKeys("Class 2");
}
}
TestNG XML File
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="System Testing" parallel="none" thread-count="1">
<test name="MenuTest" verbose="0">
<classes>
<class name="com.pack1.ClassA" />
<class name="com.pack1.ClassB" />
<class name="com.pack1.Init" />
</classes>
</test>
</suite>
Output
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running TestSuite
BS
Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 16311
Only local connections are allowed.
Mar 09, 2018 2:33:59 PM org.openqa.selenium.remote.ProtocolHandshake.createSession
INFO: Detected dialect: OSS
classATest
classBTest
AS
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.541 sec - in TestSuite

Test framework architecture using Selenium WebDriver and TestNG

guys. I trying to solve a problem with parallel running using RC Webdriver and TestNG, but unfortunately, I can't find solution last few hours. Maby you will see the code, and show me what, I actually doing wrong.
Goal:
Create architecture using RC WebDriver and TestNG, with an ability to run tests on a remote machine.
Main settings class is Sut:
private RemoteWebDriver driver = null;
#BeforeClass
public WebDriver getWebDriver() {
DesiredCapabilities dc = new DesiredCapabilities();
FirefoxProfile fp = new FirefoxProfile();
dc.setCapability(FirefoxDriver.PROFILE, fp);
dc.setBrowserName(DesiredCapabilities.firefox().getBrowserName());
try {
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), dc);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return driver;
}
#AfterClass
public void tearDown() {
driver.quit();
}
In this class we have two methods: getWebDriver() - for setup our remote webdriver, and tearDown() - for close web-page, when a test will be complete.
Class BaseStep:
private static ThreadLocal<Sut> sut = new ThreadLocal<Sut>();
public static Sut getSut() {
Sut currentSut = sut.get();
if (currentSut == null) {
currentSut = new Sut();
}
return currentSut;
}
It's an additional layer, which create 'new state for each new thread'.
Few page objects:
public class FacebookPage {
public void testLink() {
getSut().getWebDriver().get("http://facebook.com");
}
}
public class GooglePage {
public void testLink() {
getSut().getWebDriver().get("http://google.com");
}
}
And scenarious classes:
public class VerifyGooglePage {
GooglePage googlePage = new GooglePage();
#Test
public void verifyGoogleMainPage() {
googlePage.testLink();
}
}
public class VerifyFacebookPage {
Facebook facebookPage = new Facebook();
#Test
public void verifyFacebookeMainPage() {
facebookPage.testLink();
}
}
And my and testNG.xml file for running
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="1" name="Suite" parallel="tests">
<test name="FirstTest">
<classes>
<class name="scenarious.VerifyGooglePage"/>
</classes>
</test> <!-- Test -->
<test name="SecondTest">
<classes>
<class name="scenarious.VerifyFacebookPage"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
The problems is: When test complete, browser is not closed.
the Picture
I watched a lot of tutorials and articles in internet about it, but in no-one I cant found solution for my case. Could you please help me to find what I doing wrong.

Parameterized Selenium Tests in Parallel with TestNG

First of all, sorry for my english, it's not so perfect :)
So I'm facing with the following problem: I'm trying to run parallel tests in different browsers using Selenium Grid and TestNg and I pass the parameters in the #BeforeTest method. My problem is that when every test get initialized, it seems that they will use the last test's parameters. So in this example when I run the test, it will open two Chrome, instead of one Firefox and one Chrome.
(The browser.getDriver() method returns a RemoteWebDriver)
TestNG.xml:
<suite thread-count="2" verbose="10" name="testSuite" parallel="tests">
<test name="nameOfTheTestFirefox">
<parameter name="platform" value="windows"/>
<parameter name="browserVersion" value="32"/>
<parameter name="browserName" value="firefox"/>
<classes>
<class name="example.test.login.LoginOverlayTest"/>
</classes>
</test> <!-- nameOfTheTestFirefox -->
<test name="nameOfTheTestChrome">
<parameter name="platform" value="windows"/>
<parameter name="browserVersion" value="38"/>
<parameter name="browserName" value="chrome"/>
<classes>
<class name="example.test.login.LoginOverlayTest"/>
</classes>
</test> <!-- nameOfTheTestChrome -->
</suite> <!-- testSuite -->
The AbstractTest class:
public class SeleniumTest {
private static List<WebDriver> webDriverPool = Collections.synchronizedList(new ArrayList<WebDriver>());
private static ThreadLocal<WebDriver> driverThread;
public static BrowserSetup browser;
#Parameters({ "browserName", "browserVersion", "platform"})
#BeforeTest()
public static void beforeTest(String browserName, #Optional("none") String browserVersion, String platform) throws WrongBrowserException, WrongPlatformException {
final BrowserSetup browser = new BrowserSetup(browserName, browserVersion, platform);
driverThread = new ThreadLocal<WebDriver>() {
#Override
protected WebDriver initialValue() {
final WebDriver webDriver = browser.getDriver();
webDriverPool.add(webDriver);
return webDriver;
}
};
}
public static WebDriver getDriver() {
return driverThread.get();
}
#AfterTest
public static void afterTest() {
for (WebDriver driver : webDriverPool) {
driver.quit();
}
}
}
And my example #Tests:
#Test
public void test1() throws InterruptedException {
WebDriver driver = getDriver();
System.out.println("START: test1");
driver.get("http://google.com");
Thread.sleep(5000);
System.out.println("END: test1, title: " + driver.getTitle());
}
#Test
public void test2() throws InterruptedException {
WebDriver driver = getDriver();
System.out.println("START: test2");
driver.get("http://amazon.com");
Thread.sleep(5000);
System.out.println("END: test2, title: " + driver.getTitle());
}
#Test
public void test3() throws InterruptedException {
WebDriver driver = getDriver();
System.out.println("START: test3");
driver.get("http://stackoverflow.com");
Thread.sleep(5000);
System.out.println("END: test3, title: " + driver.getTitle());
}
So my question is how can I run the tests in parallel with the given parameters in separate threads?
Thanks in advance!
Peter
Don't make the fields static.
private static List<WebDriver> webDriverPool = Collections.synchronizedList(new ArrayList<WebDriver>());
private static ThreadLocal<WebDriver> driverThread;
public static BrowserSetup browser;
beforeTest() and afterTest() shouldn't be static if you want to run it in parallel, or make it synchronized to have it thread safe. Also, you do not use declared variable:
public static BrowserSetup browser;
at all, or you missed something there since you also have:
final BrowserSetup browser = new BrowserSetup(browserName, browserVersion, platform);
inside beforeTest(...)

Categories

Resources