Why CrossBrowser Automated Script Throws Error in Edge Browser? - selenium

Guys i Was Doing Cross Browser Automation in Chrome, FireFox and Edge . I Cant Able To Complete The Test Script in Edge Browser. I Was Getting an Error Message
"org.openqa.selenium.WebDriverException: Unknown error (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 42 milliseconds
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'rcktechiess-06', ip: '192.168.1.44', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_171'
Driver info: org.openqa.selenium.edge.EdgeDriver
Capabilities [{applicationCacheEnabled=true, InPrivate=false, pageLoadStrategy=normal, platform=ANY, acceptSslCerts=true, browserVersion=42.17134.1.0, platformVersion=10, locationContextEnabled=true, webStorageEnabled=true, browserName=MicrosoftEdge, takesScreenshot=true, takesElementScreenshot=true, platformName=windows}]
Session ID: B339099D-F7C6-41A7-A6E6-12D22C3D9937
I Have Attched Image For Exception. Please Check it
**Test 1 Code Using Testng**
package Crossbrowser;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class Test1 {
WebDriver driver;
#BeforeTest
#Parameters("browser")
public void setup(String browser) throws Exception
{
//Check if parameter passed from TestNG is 'firefox'
if(browser.equalsIgnoreCase("firefox"))
{
//create firefox instance
driver = new FirefoxDriver();
}
//Check if parameter passed as 'chrome'
else if(browser.equalsIgnoreCase("chrome"))
{
//set path to chromedriver.exe
System.setProperty("webdriver.chrome.driver", "F:\\New folder\\chromedriver.exe");
//create chrome instance
driver = new ChromeDriver();
}
//Check if parameter passed as 'Edge'
else if(browser.equalsIgnoreCase("Edge"))
{
//set path to IE.exe
System.setProperty("webdriver.edge.driver","F:\\New folder (2)\\MicrosoftWebDriver (1).exe");
//create Edge instance
driver = new EdgeDriver();
}
else
{
//If no browser passed throw exception
throw new Exception("Browser is not correct");
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Test
public void testParameterWithXML() throws InterruptedException
{
driver.get("http://xxxxxxxxxx/");
driver.manage().window().maximize();
driver.findElement(By.xpath("/html[1]/body[1]/div[2]/header[1]/ss-header[1]/div[1]/div[1]/div[1]/span[1]/a[1]")).click();
Thread.sleep(2000);
//Find user name
WebElement userName = driver.findElement(By.xpath("/html[1]/body[1]/div[2]/div[1]/div[1]/ss-auth-form[1]/md-card[1]/ss-login-form[1]/div[1]/form[1]/input[1]"));
//Fill user name
userName.sendKeys("koushick#rcktechiees.com");
//Find password
WebElement password = driver.findElement(By.xpath("/html[1]/body[1]/div[2]/div[1]/div[1]/ss-auth-form[1]/md-card[1]/ss-login-form[1]/div[1]/form[1]/input[2]"));
//Fill password
password.sendKeys("1234567890");
Thread.sleep(2000);
driver.findElement(By.xpath("//form[#name='myForm']//ss-submit-button[#label='Log In']//input[#class='submit']")).click();
Thread.sleep(1000);
Test2 obj = PageFactory.initElements(driver, Test2.class);
Thread.sleep(2000);
try
{
Actions a1 = new Actions(driver);
a1.moveToElement(obj.getE1()).click(obj.getE2()).build().perform();
}
catch(Exception e)
{
System.out.println("Can't Click on The Elemnet");
}
Thread.sleep(2000);
try
{
Actions a2 = new Actions(driver);
a2.moveToElement(obj.getE3()).click(obj.getE3()).build().perform();
}
catch(Exception e)
{
System.out.println("Can't Click");
}
Thread.sleep(2000);
try
{
Actions a3 = new Actions(driver);
a3.moveToElement(obj.getE4()).click(obj.getE5()).build().perform();
}
catch(Exception e)
{
System.out.println("Can't Click on The Elemnet");
}
Thread.sleep(2000);
obj.getE6().sendKeys("ss#gmail.com");
Thread.sleep(2000);
obj.getE7().click();
Thread.sleep(2000);
obj.getE8().click();
Thread.sleep(2000);
driver.navigate().to("http://XXXXXXXXXXXX/");
Thread.sleep(2000);
driver.findElement(By.xpath("//a[#classname='nav-link men']")).click();
Thread.sleep(2000);
}
#AfterTest
public void MatchitnowWithXML() throws InterruptedException
{
Test2 obj1 = PageFactory.initElements(driver, Test2.class);
Actions a4 = new Actions(driver);
a4.moveToElement(obj1.getE9()).click(obj1.getE9()).build().perform();
Thread.sleep(2000);
obj1.getE10().click();
Thread.sleep(2000);
obj1.getE11().click();
Thread.sleep(2000);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollTop = arguments[1];",driver.findElement(By.id("sylnk-it")), 500);
Thread.sleep(2000);
obj1.getE12().click();
Thread.sleep(2000);
Actions a5 = new Actions(driver);
a5.moveToElement(obj1.getE13()).click(obj1.getE13()).build().perform();
Thread.sleep(2000);
try
{
driver.findElement(By.xpath("//button[#class='cal-sly']")).click();
}
catch (Exception e)
{
System.out.println("Not Visible To Click");
}
Thread.sleep(2000);
driver.navigate().back();
Thread.sleep(2000);
driver.navigate().back();
Thread.sleep(2000);
try
{
Actions a6 = new Actions(driver);
a6.moveToElement(obj1.getE14()).click(obj1.getE15()).build().perform();
}
catch(Exception e)
{
System.out.println("Can't Move To The Element and Click");
}
Thread.sleep(2000);
try
{
Actions a7 = new Actions(driver);
a7.moveToElement(obj1.getE16()).click(obj1.getE17()).build().perform();
}
catch(Exception e)
{
System.out.println("Can't Click on the Element !");
}
Thread.sleep(3000);
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollBy(0,250)");
Thread.sleep(1000);
try
{
Actions a8 = new Actions(driver);
a8.moveToElement(obj1.getE18()).click(obj1.getE19()).build().perform();
}
catch(Exception e)
{
System.out.println("Can't Move To The Element and Click");
}
Thread.sleep(2000);
try
{
Actions a9 = new Actions(driver);
a9.moveToElement(obj1.getE20()).click().build().perform();
}
catch(Exception e)
{
System.out.println("Can't Click");
}
Thread.sleep(2000);
try
{
driver.findElement(By.xpath("/html[1]/body[1]/div[2]/ss-app[1]/ss-search-page[1]/div[2]/ss-search-filters[1]/ss-slide-filter[1]/ss-search-filter[1]/div[1]/div[2]/span[1]")).click();
}
catch(Exception e)
{
System.out.println("Can't Click");
}
}
}
Down am Attaching Page ObjectModel Framework Code
**Test2 Code Using POM Framework Using GET Method**
package Crossbrowser;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class Test2 {
public WebElement getE1() {
return e1;
}
public WebElement getE2() {
return e2;
}
public WebElement getE3() {
return e3;
}
public WebElement getE4() {
return e4;
}
public WebElement getE5() {
return e5;
}
public WebElement getE6() {
return e6;
}
public WebElement getE7() {
return e7;
}
public WebElement getE8() {
return e8;
}
public WebElement getE9() {
return e9;
}
public WebElement getE10() {
return e10;
}
public WebElement getE11() {
return e11;
}
public WebElement getE12() {
return e12;
}
public WebElement getE13() {
return e13;
}
public WebElement getE14() {
return e14;
}
public WebElement getE15() {
return e15;
}
public WebElement getE16() {
return e16;
}
public WebElement getE17() {
return e17;
}
public WebElement getE18() {
return e18;
}
public WebElement getE19() {
return e19;
}
public WebElement getE20() {
return e20;
}
#FindBy(xpath="/html[1]/body[1]/div[2]/header[1]/ss-header[1]/div[1]/div[1]/ss-user-dropdown[1]/div[1]/ss-svg-icon[1]/span[1]/i[1]")
private WebElement e1;
#FindBy(xpath="/html[1]/body[1]/div[2]/header[1]/ss-header[1]/div[1]/div[1]/ss-user-dropdown[1]/div[1]/div[1]/a[9]")
private WebElement e2;
#FindBy(xpath="//button[#id='ranomizeButton']")
private WebElement e3;
#FindBy(xpath="/html/body/div[2]/header/ss-header/div/div[2]/ss-user-dropdown/div")
private WebElement e4;
#FindBy(xpath="/html/body/div[2]/header/ss-header/div/div[2]/ss-user-dropdown/div/div/a[3]")
private WebElement e5;
#FindBy(xpath="/html[1]/body[1]/div[2]/div[4]/div[2]/div[1]/div[2]/div[2]/div[1]/div[1]/input[1]")
private WebElement e6;
#FindBy(xpath="/html[1]/body[1]/div[2]/div[4]/div[2]/div[1]/div[2]/div[2]/div[1]/button[1]")
private WebElement e7;
#FindBy(xpath="/html[1]/body[1]/div[2]/div[5]/div[1]/div[1]/div[2]/div[1]/div[1]/button[1]")
private WebElement e8;
#FindBy(xpath="/html/body/div[2]/ss-app/ss-search-page/div[4]/div[2]/ss-products-list/div[2]/span[3]/ss-product-cell/div/div[4]/span")
private WebElement e9;
#FindBy(xpath="/html/body/div[2]/ss-app/div[6]/div/ss-auth-form/md-card/div[1]/span[1]/div/div[2]/label/span")
private WebElement e10;
#FindBy(id="C5")
private WebElement e11;
#FindBy(id="slynk_save")
private WebElement e12;
#FindBy(xpath="/html[1]/body[1]/div[2]/ss-app[1]/ss-header[1]/div[1]/div[1]/span[2]")
private WebElement e13;
#FindBy(xpath="/html[1]/body[1]/div[2]/ss-app[1]/ss-search-page[1]/div[4]/div[2]/ss-products-list[1]/div[2]/span[1]/ss-product-cell[1]/div[1]/div[5]")
private WebElement e14;
#FindBy(xpath="/html[1]/body[1]/div[2]/ss-app[1]/ss-search-page[1]/div[4]/div[2]/ss-products-list[1]/div[2]/span[1]/ss-product-cell[1]/div[1]/div[5]/a[2]/span[1]/i[1]")
private WebElement e15;
#FindBy(xpath="//ss-product-cell[#id='110743~Dresslily~womens-tops~womens-tops']//div[#class='product-cell-container extended-cell']//div[#class='bottom-icons']")
private WebElement e16;
#FindBy(xpath="//span[#id='~110743~Stylish Lace Embellished Short Sleeve Scoop Neck Womens TShirt~Dresslily~Dresslily~Dresslily~womens-tops~womens-tops~~undefined~$4.99~$9.67~~^^womens-tops^womens-clothes^women ']//i[#class='icon-12']")
private WebElement e17;
#FindBy(xpath="//ss-product-cell[#id='304028~GuessFactory~shorts~shorts']//div[#class='product-cell-container extended-cell']//div[#class='bottom-icons']")
private WebElement e18;
#FindBy(xpath="//span[#id='~304028~Shelby Denim Shorts~GuessFactory~Guess Factory~Guess Factory~shorts~shorts~~undefined~~$44.99~~^^shorts^womens-clothes^women ']//i[#class='icon-12']")
private WebElement e19;
#FindBy(xpath="/html[1]/body[1]/div[2]/ss-app[1]/ss-search-page[1]/div[2]/ss-search-filters[1]/ss-slide-filter[1]/ss-search-filter[1]/span[1]")
private WebElement e20;
PS: While Executing The Test Script are Sucessfully Passing in Chrome and FireFox. But Failing in Edge Only at The Middle of Automation Some Kind of Stack Error. Down Am Also Attching The XML Please Give Me a Solution To Find a BetterWay.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" >
<test name="FirefoxTest">
<parameter name="browser" value="firefox">
<classes>
<class name="Crossbrowser.Test1"/>
</classes>
</parameter>
</test> <!-- Test -->
<test name="chromeTest">
<parameter name="browser" value="chrome">
<classes>
<class name="Crossbrowser.Test1"/>
</classes>
</parameter>
</test> <!-- Test -->
<test name="EdgeTest">
<parameter name="browser" value="Edge">
<classes>
<class name="Crossbrowser.Test1"/>
</classes>
</parameter>
</test> <!-- Test -->
</suite> <!-- Suite -->

Related

Running two Test cases(method) in two same browsers using Parallel testing in TestNG Selenium

I am trying to execute parallel testing in tow test cases(methods) in two same browsers.
But when I run, it opens two same browsers but the execution is performed in one browser, means two test methods executed in one browser.
BaseClass.Java
public class BaseClass {
public WebDriver driver;
public FBLoginPage loginPage;
#BeforeMethod
public void launch() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demo.guru99.com/test/newtours/");
loginPage = new FBLoginPage();
PageFactory.initElements(driver, loginPage);
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
FBLoginPage.java (Page Class)
public class FBLoginPage {
#FindBy(xpath = "//input[#name='userName']")
public WebElement userName;
#FindBy(xpath = "//input[#name='password']")
public WebElement password;
#FindBy(xpath = "//input[#name='submit']")
public WebElement submitButton;
#FindBy(xpath = "//a[normalize-space()='REGISTER']")
public WebElement registerLink;
public void doLogin(String uname, String pwd) throws Exception {
Thread.sleep(2000);
userName.sendKeys(uname);
password.sendKeys(pwd);
Thread.sleep(2000);
submitButton.click();
}
public void clickOnRegisterLink() throws Exception {
Thread.sleep(2000);
registerLink.click();
}
}
FBLoginTest.java (Test Class)
public class FBLoginTest extends BaseClass {
#Test(priority = 1)
public void loginTest_ValidCredential() throws Exception {
String beforeLoginURL = driver.getCurrentUrl();
Thread.sleep(1000);
loginPage.doLogin("abc#gmail.com", "password");
Thread.sleep(2000);
String afterLoginURL = driver.getCurrentUrl();
Assert.assertEquals(true, !(beforeLoginURL.equals(afterLoginURL)), "Login unSuccessful");
}
#Test(priority = 2)
public void clickOnSecurityProject_LoginPage() throws Exception {
String beforeLoginURL = driver.getCurrentUrl();
loginPage.clickOnRegisterLink();
Thread.sleep(2000);
String afterLoginURL = driver.getCurrentUrl();
Assert.assertEquals(true, !(beforeLoginURL.equals(afterLoginURL)), "Test case fail");
}
}
testNG.xml
<suite name="Suite">
<test thread-count="2" name="Test" parallel="methods">
<classes>
<class name="demo.TestCases.FBLoginTest" />
</classes>
</test>
</suite>
In the above code, when I run it through xml, then two same(chrome) browser are opening but exction is performed in one browser.
Please help me to solve this problem
Thank You

Parallel methods do not run as expected

I need all the tests to be part of single class and run these tests in parallel. I'm using parallel="methods" in Testng.xml. I have class like
Public class DemoParallel{
#Test
/* some code to launch Google.*/
#Test
/* some code to launch Facebook*/
}
Actual : 2 instances of chrome launches. Google test is running completely.Facebook test is only launched but does not run. Gets hanged. Only one test passes and also have tried implementing listeners but no luck.
Any suggestions would be helpful.
Local Driver Factory :
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
class LocalDriverFactory {
static WebDriver createInstance(String browserName) {
WebDriver driver = null;
if (browserName.toLowerCase().contains("firefox")) {
System.setProperty("webdriver.firefox.marionette","path to driver exe");
driver = new FirefoxDriver();
return driver;
}
if (browserName.toLowerCase().contains("internet")) {
driver = new InternetExplorerDriver();
return driver;
}
if (browserName.toLowerCase().contains("chrome")) {
System.setProperty("webdriver.chrome.driver","path to driver exe");
driver = new ChromeDriver();
return driver;
}
return driver;
}
}
use ThreadLocal class as follows :
public class LocalDriverManager {
private static ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
public static WebDriver getDriver() {
return webDriver.get();
}
static void setWebDriver(WebDriver driver) {
webDriver.set(driver);
}
}
Create Webdriver Listener class :
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
public class WebDriverListener implements IInvokedMethodListener {
#Override
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
WebDriver driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
}
}
#Override
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
WebDriver driver = LocalDriverManager.getDriver();
if (driver != null) {
driver.quit();
}
}
}
}
Test Class
public class ThreadLocalDemo {
#Test
public void testMethod1() {
invokeBrowser("https://www.google.com/");
}
#Test
public void testMethod2() {
invokeBrowser("http://www.facebook.com");
}
private void invokeBrowser(String url) {
System.out.println("Thread id = " + Thread.currentThread().getId());
System.out.println("Hashcode of webDriver instance = " + LocalDriverManager.getDriver().hashCode());
LocalDriverManager.getDriver().get(url);
}
}
Suite Xml File :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="methods">
<listeners>
<listener class-name="path-to-class-WebDriverListener"></listener>
</listeners>
<test name="Test">
<parameter name="browserName" value="firefox"></parameter>
<classes>
<class name="path-to-class-ThreadLocalDemo" />
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Selenium "no such session" error on TestNG testing.xml

I am trying to run a simple test with crossbrowsers using testing.xml of TestNG. Script runs fine on the first run which is Chrome. But gives "no such session" error on the firefox test beginning.
I simplified the codes to make it easy to read. I hope it helps.
Here's my TestNG testing.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="DefaultSuite" thread-count="1" parallel="tests">
<test name="ChromeTest">
<parameter name="browser" value="Chrome" />
<classes>
<class name="loginTest">
</class>
</classes>
</test>
<test name="FirefoxTest">
<parameter name="browser" value="Firefox" />
<classes>
<class name="loginTest">
</class>
</classes>
</test>
</suite>
And here's my code
public class loginTest {
private static WebDriver driver;
#BeforeTest
#Parameters("browser")
public void testSetup(String browser) throws Exception {
//Check if parameter passed from TestNG is 'firefox'
if(browser.equalsIgnoreCase("firefox")){
driver = webBrowsers.browserAl("Firefox");
}
//Check if parameter passed as 'chrome'
else if(browser.equalsIgnoreCase("chrome")){
driver = webBrowsers.browserAl("Chrome");
}
else{
//If no browser passed throw exception
throw new Exception("Browser is not correct");
}
}
#Test(priority=0)
public void LoginTest(){
driver.get("http://www.hurriyet.com.tr/");
}
#AfterTest
public void kapat() {
webBrowsers.closeDriver();
}
}
and finally my webBrowsers.class
public class webBrowsers {
private static WebDriver driver = null;
private static String browserName;
public static WebDriver browserAl(String browserName) {
if (browserName.equals("Firefox")) {
if (driver == null) {
System.setProperty("webdriver.gecko.driver","./drivers/geckodriver.exe");
driver = new FirefoxDriver();
}
} else if (browserName.equals("Edge")) {
if (driver == null) {
System.setProperty("webdriver.edge.driver", "./drivers/MicrosoftWebDriver.exe");
driver = new EdgeDriver();
}
} else if (browserName.equals("Chrome")) {
if (driver == null) {
System.setProperty("webdriver.chrome.driver","./drivers/chromedriver.exe");
driver = new ChromeDriver();
}
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
return driver;
}
public static void closeDriver() {
driver.close();
}
}
The problem is in your class webBrowsers. You are working with a static webdriver instance. So for the first <test> execution the driver instance will not be null and it would get instantiated properly. But when you execute the second <test> tag, the condition driver == null would be false, and you end up getting reference to the webdriver object that was created for the previous <test> tag. To make matters worse, you have a #AfterTest method which cleans up the driver instance as well. So you are now essentially working with a valid webdriver instance but for which the opened session has already been cleaned up.
End result : Your error.
Here's a cleaned up version of your code that should get past this problem.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class WebBrowsers {
public static WebDriver browserAl(String browserName) {
WebDriver driver = null;
if (browserName.equals("Firefox")) {
System.setProperty("webdriver.gecko.driver", "./drivers/geckodriver.exe");
driver = new FirefoxDriver();
} else if (browserName.equals("Edge")) {
System.setProperty("webdriver.edge.driver", "./drivers/MicrosoftWebDriver.exe");
driver = new EdgeDriver();
} else if (browserName.equals("Chrome")) {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
driver = new ChromeDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
return driver;
}
public static void closeDriver(WebDriver driver) {
if (driver != null) {
driver.quit();
}
}
}
Here's how your test class would look like
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class LoginTest {
private WebDriver driver;
#BeforeTest
#Parameters("browser")
public void testSetup(String browser) throws Exception {
//Check if parameter passed from TestNG is 'firefox'
if (browser.equalsIgnoreCase("firefox")) {
driver = WebBrowsers.browserAl("Firefox");
}
//Check if parameter passed as 'chrome'
else if (browser.equalsIgnoreCase("chrome")) {
driver = WebBrowsers.browserAl("Chrome");
} else {
//If no browser passed throw exception
throw new Exception("Browser is not correct");
}
}
#Test
public void loginTest() {
driver.get("http://www.hurriyet.com.tr/");
}
#AfterTest
public void kapat() {
WebBrowsers.closeDriver(driver);
}
}

How to close a window after running each test case in Selenium IntelliJ?

I have a set of three test cases, and I want to avoid keeping open multiple browser windows since I automated this process in Selenium. Is there a way to close a browser after each test case is finished without giving an error?
Using close() and quit() both give me error codes of 1.
We use below approach to handle these issue.
1) create a base class which has beforeSuite , beforeTest , afterTest , afterSuite methods which will run always.
2) Each test plan should extend this class to create driver and close the driver.
BasePage.java
package com.test.test3;
import java.lang.reflect.Method;
import java.util.Date;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
public class BasePage {
public WebDriver driver = null;
private Date start;
/*
* Below method will initialize the driver once test method started
* execution
*/
public void initializeDriver(WebDriver driver) {
this.driver = driver;
}
/*
* Below method will kill driver
*/
public void tearDown() {
if (this.driver != null) {
this.driver.quit();
}
}
#AfterMethod(alwaysRun = true)
public void afterTestMethod(Method method) {
// Clean ups for test level services
tearDown();
}
#AfterSuite(alwaysRun = true)
public void afterTestSuite() {
tearDown();
}
}
Testplan.java
package com.test.test3;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class TestPlan extends BasePage{
#Test(groups = { "test"})
public void test() {
FirefoxDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
System.out.println("TestAutomation test");
}
#Test(groups = { "test"})
public void test1() {
FirefoxDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
System.out.println("TestAutomation test");
}
#Test(groups = { "test"})
public void test2() {
FirefoxDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
System.out.println("TestAutomation test");
}
}
testNg.xml
<suite name="API TEST CASES">
<test name="api test" parallel="methods">
<groups>
<run>
<include name="test" />
</run>
</groups>
<classes>
<class name="com.test.test3.TestPlan" />
</classes>
</test>

Two empty instances of firefox browser opens testng selenium webdriver

I have been having this problem that when i run a testng test suite firefox open three instances of browser and execute my tests on the third instance leaving first two instances completely empty, what i want my firefox driver to do is to create just one instance of the browser and perform my tests on it.My testing.xml looks like
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestNG Suite" parallel="false">
<test name="Firefox Test">
<parameter name="browserName" value="firefox"></parameter>
<classes>
<class name="Publisher.CreateSites" />
</classes>
</test> <!-- Test -->
<test name="Chrome Test">
<parameter name="browserName" value="chrome"></parameter>
<classes>
<class name="Publisher.CreateSites" />
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
and my java class looks like
public class CreateSites
{
private ReadExcel fr = new ReadExcel();
public WebDriver driver = new FirefoxDriver();
#BeforeTest
#Parameters("browserName")
public void setup(String browserName) throws Exception{
//Check if parameter passed from TestNG is 'firefox'
if(browserName.equalsIgnoreCase("firefox"))
{
//create firefox instance
driver = new FirefoxDriver();
}
//Check if parameter passed as 'chrome'
else if(browserName.equalsIgnoreCase("chrome"))
{
//set path to chromedriver.exe You may need to download it from http://code.google.com/p/selenium/wiki/ChromeDriver
System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
//create chrome instance
driver = new ChromeDriver();
}
else
{
//If no browser passed throw exception
throw new Exception("Browser is not correct");
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://portal.admaxim.com/main3/home.jsf");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
}
#Test(priority=0)
public void loginTest()
{
fr = new ReadExcel();
fr.readexel("TestNGExcelFile", "Create_Site");
driver.findElement(By.id("loginForm:userName")).click();
driver.findElement(By.id("loginForm:userName")).clear();
driver.findElement(By.id("loginForm:userName")).sendKeys(fr.List1.get(0));
driver.findElement(By.id("loginForm:password")).click();
driver.findElement(By.id("loginForm:password")).clear();
driver.findElement(By.id("loginForm:password")).sendKeys(fr.List1.get(1));
driver.findElement(By.id("loginForm:submit")).click();
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
}
#Test(priority=1)
public void moveToPublisher() throws InterruptedException
{
driver.findElement(By.xpath(".//*[#id='homeForm:menuPublisherOption1']/img")).click();
Thread.sleep(4000);
}
#Test(priority=2)
public void clickOnCreateSiteLink()
{
driver.findElement(By.xpath(".//*[#id='deliveryImg']")).click();
driver.findElement(By.xpath(".//*[#id='homeForm:welcomePubView:createSiteLbl']")).click();
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
}
#Test(priority=3)
public void selectAccount() throws InterruptedException
{
Thread.sleep(3000);
Select account = new Select(driver.findElement(By.xpath(".//*[#id='availableSubAccountsList']")));
account.selectByVisibleText("droidpubsub");
driver.findElement(By.xpath(".//*[#id='selectSubAccount_div']/table/tbody/tr[2]/td[2]/input[1]")).click();
}
#Test(priority=4)
public void selectBasicInfo()
{
driver.findElement(By.xpath(".//*[#id='accordion']/ul/li[2]/a")).click();
driver.findElement(By.id("categoryForm:name")).click();
driver.findElement(By.id("categoryForm:name")).clear();
driver.findElement(By.id("categoryForm:name")).sendKeys(fr.List1.get(2));
driver.findElement(By.id("categoryForm:externalSiteID")).click();
driver.findElement(By.id("categoryForm:externalSiteID")).clear();
driver.findElement(By.id("categoryForm:externalSiteID")).sendKeys(fr.List1.get(3));
driver.findElement(By.id("categoryForm:siteURL")).click();
driver.findElement(By.id("categoryForm:siteURL")).clear();
driver.findElement(By.id("categoryForm:siteURL")).sendKeys(fr.List1.get(4));
driver.findElement(By.id("categoryForm:description")).click();
driver.findElement(By.id("categoryForm:description")).clear();
driver.findElement(By.id("categoryForm:description")).sendKeys(fr.List1.get(5));
}
#Test(priority=5)
public void setTargeting() throws InterruptedException
{
driver.findElement(By.xpath(".//*[#id='accordion']/ul/li[3]/a")).click();
Thread.sleep(2000);
// Select values from Demographic tab
// Select Gender.
WebElement selectGender = driver.findElement(By.id("categoryForm:demographics_avail_gender"));
Select genderOptions = new Select(selectGender);
for(int i= 0; i<2; i++)
{
genderOptions.selectByIndex(i);
}
driver.findElement(By.xpath(".//*[#id='genderDemographicDiv']/table/tbody/tr[3]/td[2]/input[1]")).click();
// Select Age.
driver.findElement(By.xpath(".//*[#id='ageDemographicTabBtnTd']")).click();
WebElement selectAge = driver.findElement(By.id("categoryForm:demographics_avail_age"));
Select Ageoptions = new Select(selectAge);
for(int i= 0; i<5; i++)
{
Ageoptions.selectByIndex(i);
}
driver.findElement(By.xpath(".//*[#id='ageDemographicDiv']/table/tbody/tr[3]/td[2]/input[1]")).click();
// Select Occupation type.
driver.findElement(By.xpath(".//*[#id='occupationTypeDemographicTabBtnTd']/a")).click();
WebElement selectOccupationType = driver.findElement(By.id("categoryForm:demographics_avail_occupationType"));
Select occupationTypeOptions = new Select(selectOccupationType);
for(int i= 0; i<9; i++)
{
occupationTypeOptions.selectByIndex(i);
}
driver.findElement(By.xpath(".//*[#id='occupationTypeDemographicDiv']/table/tbody/tr[3]/td[2]/input[1]")).click();
// Select Occupation Industry.
driver.findElement(By.xpath(".//*[#id='occupationIndustryDemographicTabBtnTd']/a")).click();
WebElement selectOccupationIndustry = driver.findElement(By.id("categoryForm:demographics_avail_occupationIndustry"));
Select occupationIndustryOptions = new Select(selectOccupationIndustry);
for(int i= 0; i<13; i++)
{
occupationIndustryOptions.selectByIndex(i);
}
driver.findElement(By.xpath(".//*[#id='occupationIndustryDemographicDiv']/table/tbody/tr[3]/td[2]/input[1]")).click();
}
/*#Test
public void logout()
{
driver.findElement(By.xpath(".//*[#id='dd_Icon']")).click();
driver.findElement(By.xpath(".//*[#id='homeForm:top:lnkLogoutTxt']")).click();
}
#AfterTest
public void closeBrowser()
{
driver.quit();
}*/
}
These are the only relevant parts of your code:
public class CreateSites
{
public WebDriver driver = new FirefoxDriver();
#BeforeTest
public void setup(String browserName) throws Exception {
//create firefox instance
driver = new FirefoxDriver();
}
/*
#AfterTest
public void closeBrowser()
{
driver.quit();
}*/
}
everything else is not relevant to your problem.
The first line of your class new FirefoxDriver() opens a Firefox browser. Before every test, you again call new FirefoxDriver() which opens another browser. Lastly, you commented out the driver.quit(), which would normally close the browser!
What you probably want is:
public class CreateSites
{
public WebDriver driver; // do not open Firefox here!
#BeforeTest
public void setup(String browserName) throws Exception {
//create firefox instance
driver = new FirefoxDriver();
}
#AfterTest // make sure this runs!
public void closeBrowser()
{
driver.quit();
}
}