Webdriver object gets overwritten when tests are run in parallel - java

I'm writing Java based selenium-web-driver tests to run a parallel cross browser test using testng .
I have set the tests to run parallel on my xml file.The file looks like this :
<suite name="TestSuite" thread-count="2" parallel="tests" >
<test name="ChromeTest">
<parameter name="browser" value="Chrome" />
<classes>
<class name="test.login"/>
<class name="test.main"/>
<class name="test.logout"/>
</classes>
</test>
<test name="FirefoxTest">
<parameter name="browser" value="Firefox" />
<classes>
<class name="test.login"/>
<class name="test.main"/>
<class name="test.logout"/>
</classes>
</test>
But when i run test, both browser instances gets opened (Chrome opens first and starts execution and after a delay Firefox is opened).
In that case , the driver object gets overwritten by Firefox driver and chrome stops execution.Tests continue execution on Firefox and
gets completed successfully.
The structure of the project is like this :
Created a driverbase.class to load driver corresponding to browser which has my #Beforesuite.
Crteated individual classes for pages.(Eg: login.class , main.class etc) which has only #Test method and have extended driverbase class to get driver.
Test are run suceessfully when i set parallel to none on xml file
<suite name="TestSuite" thread-count="2" parallel="none" >
How can i overcome this issue? How to run tests in parallel without this issue?
The driverbase class is like this :
public class driverbase {
private String baseUrl;
private String nodeUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
public static WebDriver driver = null;
/**
* This function will execute before each Test tag in testng.xml
* #param browser
* #throws Exception
*/
#BeforeSuite
#Parameters("browser")
public WebDriver setup(String browser) throws Exception{
//Check if parameter passed from TestNG is 'firefox'
if(browser.equalsIgnoreCase("firefox")){
System.out.println("Browser : "+browser);
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
//create firefox instance
driver = new FirefoxDriver(profile);
}
//Check if parameter passed as 'chrome'
else if(browser.equalsIgnoreCase("chrome")){
System.out.println("Browser : "+browser);
//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");
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
//create chrome instance
driver = new ChromeDriver(options);
}
else{
//If no browser passed throw exception
System.out.println("Browser is incorrect");
throw new Exception("Browser is not correct");
}
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
Thanks for the help :)

#BeforeSuite methods are not supposed to return something. => replace by void
Your testng has 2 differents tests, but #BeforeSuite will always be run once by suite what your comment shows you doesn't expect it. => replace by #BeforeTest
When you run in //, 2 threads are settings the driver value (one with firefox, one with chrome) which explains your problem.
You can try something like:
public class driverbase {
private String baseUrl;
private String nodeUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
public WebDriver driver;
#BeforeTest
#Parameters("browser")
public void setup(String browser) throws Exception {
if(browser.equalsIgnoreCase("firefox")) {
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
driver = new FirefoxDriver(profile);
} else if(browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
driver = new ChromeDriver(options);
} else {
throw new Exception("Browser is not correct");
}
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
You should have a look on http://fluentlenium.org/ too.

To sure that same instance of webdriver won't be assigned to multiple tests. The method where driver instances are being created should be synchronized. This should solve the issue.
public synchronized void setup(String browser) throws Exception {
if(browser.equalsIgnoreCase("firefox")) {
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
driver = new FirefoxDriver(profile);
} else if(browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
driver = new ChromeDriver(options);
} else {
throw new Exception("Browser is not correct");
}
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
}

Related

Selenium, TestNg parallel run not working as expected

I have 3 test classes consisting of multiple test methods that I want to run in parallel. I'm using ThreadLocal for isolating webdriver instances per thread. When I run the tests in sequential manner everything looks fine but problem arises when I run them in parallel. Below is my suite file
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="platform" parallel="classes" thread-count="5">
<test name="platform">
<classes>
<class name="com.sat.platform.mobile.PlatformMobileIdCaptureMonitoringWf11"></class>
<class name="com.sat.platform.mobile.PlatformMobileIdVerificationMonitoringWf2"></class>
<class name="com.sat.platform.mobile.PlatformMobileIdandIVMonitoringWf3"></class>
<class name="com.sat.platform.mobile.PlatformMobileLivenessMonitoringWf6"></class>
<class name="com.sat.platform.mixed.PlatformMixedIdSimilarityMonitoringWf2and5"></class>
</classes>
</test>
</suite>
I'm initializing Webdriver in #BeforeClass in BrowserClient.java as below.
protected WebDriver driver;
private static int implicitWaitTime;
private static int explicitWaitTime;
private static int fluentWaitTime;
private static int pollingTime;
protected static WebDriverWait explicitWait;
protected static Wait<WebDriver> fluentWait;
private static String browser;
protected static Browsers browsers;
static {
Properties prop = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream("browser.properties");
try {
prop.load(stream);
} catch (IOException e) {
}
implicitWaitTime = Integer.parseInt(prop.getProperty("browser.implicit.wait.timeout"));
explicitWaitTime = Integer.parseInt(prop.getProperty("browser.explicit.wait.timeout"));
fluentWaitTime = Integer.parseInt(prop.getProperty("browser.fluent.wait.timeout"));
pollingTime = Integer.parseInt(prop.getProperty("browser.wait.polling.time"));
browser = System.getProperty("browser");
}
#BeforeClass
public void initializeEnv() throws MalformedURLException {
driver = BrowserFactory.createInstance(browser, implicitWaitTime);
DriverFactory.getInstance().setDriver(driver);
driver = DriverFactory.getInstance().getDriver();
explicitWait = new WebDriverWait(driver, explicitWaitTime);
fluentWait = new FluentWait(driver).withTimeout(Duration.of(fluentWaitTime, SECONDS))
.pollingEvery(Duration.of(pollingTime, SECONDS))
.ignoring(NoSuchElementException.class);
}
the used class here i.e BrowserFactory.java
public static WebDriver createInstance(String browser, int implicitWaitTime) throws MalformedURLException {
WebDriver driver = null;
Browsers browserEnum = Browsers.valueOf(browser);
String testVideo = ImageProcessingUtils.getAbsolutePath("digital_copy.mjpeg", false);
switch (browserEnum) {
case chrome:
ChromeOptions options = new ChromeOptions();
options.addArguments("--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream",
"--use-file-for-fake-video-capture=" + testVideo, "--start-maximized");
driver = new ChromeDriver(options);
break;
case firefox:
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("media.navigator.permission.disabled", true);
firefoxProfile.setPreference("media.navigator.streams.fake", true);
firefoxProfile .setPreference("browser.private.browsing.autostart", false);
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setProfile(firefoxProfile);
driver = new FirefoxDriver(firefoxOptions);
break;
}
}
DriverFactory.java
public class DriverFactory {
private static DriverFactory instance = new DriverFactory();
private static ThreadLocal<WebDriver> driver = new ThreadLocal<>();
private static List<WebDriver> driversList = new ArrayList();
private DriverFactory(){
}
public static DriverFactory getInstance() {
return instance;
}
public WebDriver getDriver(){
WebDriver localDriver = driver.get();
driversList.add(localDriver);
return localDriver;
}
public void setDriver(WebDriver driver){
this.driver.set(driver);
}
public static void removeDriver(){
for(WebDriver driver : driversList) {
driver.quit();
}
}
}
And my test classes extends BrowserClient.java where i can use the driver directly. One of the common method in all 3 test classes is merchant_gets_oauth_token() as shown below. The problem is when test suite is run, 3 firefox browsers are open in parallel and all of them navigates to the login page but only 1 and sometimes 2 of the tests passes while the 3rd one fails (unable to login).
#Test
public void merchant_gets_oauth_token() {
OAuth2Client client = new OAuth2Client();
String loginUrl = DslConfigFactory.getEnvConfig("portal.customer.url");
driver.get(loginUrl);
CustomerPortalLoginPage loginPage = new CustomerPortalLoginPage(driver);
log.info("----------merchant logging to customer portal to get oauth token----------");
loginPage.login(merchantUser.getEmail(), merchantUser.getPassword());
CustomerPortalHomePage homePage = new CustomerPortalHomePage(driver);
homePage.clickOnSettings();
CustomerPortalSettingsPage settingsPage = new CustomerPortalSettingsPage(driver);
settingsPage.clickOnApiCredentials();
CustomerPortalApiCredentialsPage apiCredentialsPage = new CustomerPortalApiCredentialsPage(driver);
clientCredentials = apiCredentialsPage.getOauth2ClientCredentials();
oauthToken = client.getOauthToken(clientCredentials.get("token"), clientCredentials.get("secret"));
}
I have been struggling with this problem for a while and had looked up lot of online resources without help. Maybe somebody here is able to do the RCA. Thanks in Advance!!
public static void removeDriver(){
for(WebDriver driver : driversList) {
driver.quit();
}
}
Here, replace driver.quit() with driver.close().
driver.close() method it will close only current driver. driver.close() closes all drivers.
When first instance executes removeDriver(), it will closes all windows/drivers. Then next instance try to execute removeDriver(),there driver is not available because it is already closed by previous instance of driver.so you get error.

Testng opens only one browser for parallel config

I want to run multiple tests in chrome. i.e 2 tests parallel in 2 chrome. I do have a maven project defined by the POM (testing.xml):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="mytestsuite" parallel="tests" >
<test name="case1">
<classes>
<class name="Testcases.hello1Test"></class>
</classes>
</test>
<test name="case2">
<classes>
<class name="Testcases.hello2.Test"></class>
</classes>
</test>
</suite>
Code to invoke browse is within my baseTest :
public hello1Page1 hellopage1;
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setJavascriptEnabled(true);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
chromePath = System.getProperty("user.dir") + prop.getProperty("driverrPath");
System.setProperty("webdriver.chrome.driver", chromePath);
driver = new ChromeDriver(options);
driver.get(Prop.getProperty("URL"));
hellopage1 = PageFactory.initElements(driver, helloPage1.class);
This is page class :
public class hello1Page extends BaseTest {
WebDriver driver;
public hello1Page(WebDriver driver){
this.driver = driver;
}
public hello1Page method1 {... return this;}
public hello1Page method2 {... return this;}
}
This is test class :
public class hello1Test extends BaseTest
{
#Test(priority = 0)
public void methodT1(){
hello1page.method1();
}
}
I have other tests that follow this same pattern.
What I am assuming is when I run testng.xml, It should go to baseTest 2 times and open 2 chrome then run my 2 tests in separate chrome. But somehow this is not happening. It opens only 1 chrome browser and run only 1 test.
Normally everything works fine like run single test case using maven command but issue is with parallel.
I am expecting this is root cause
hellopage1 = PageFactory.initElements(driver, helloPage1.class);
In BaseTest.
In Pages, declare
WebDriver driver;
also
public className(WebDriver driver){
this.driver = driver;
}
In Test Case
WebDriver driver;
PageClassName obj;
#Test(priority=0)
public void test(){
//Create Login Page object
objLogin = new PageClassName(driver);
List item
Try with following steps :-
Create Threadsafe Webdriver instance like this :
private static ThreadLocal webDriver = new ThreadLocal();
Use getter and setter to use driver like this :-
public static WebDriver getDriver() {
return webDriver.get();
}
static void setWebDriver(WebDriver driver) {
webDriver.set(driver);
}
Add thread-count=2 (TestNg xml file) like this :-
Hope this will help .Thank You! Refer this for more info - https://rationaleemotions.wordpress.com/2013/07/31/parallel-webdriver-executions-using-testng/

Parellel testing with TestNG - Tests only run on one browser

I have created a test suite using
DataProvider
DataFactory
and my TestNG file is sending browser details as parameters. In testNG XML I'm calling my data factory class. I'm also using browsestack for testing (although I doubt this has anything to do with the problem I"m having)
Tests run without any issues when I don't add parrellel="true" to testng file.
I have a feeling it has something to do with same driver being used by each browser, but I'm out of depth to solve this at the moment.
Any guidance is appreciated.
Here's the code.
TestNG.XML
<suite name="Suite" verbose="1" parallel="tests">
<!-- Test with Chrome -->
<test name="ChromeTest" group-by-instances="true">
<parameter name="browser" value="Chrome"></parameter>
<parameter name="browserVersion" value="47"></parameter>
<parameter name="platform" value="Windows"></parameter>
<parameter name="platformVersion" value="7"></parameter>
<classes>
<class name="Resources.TestFactory"/>
</classes>
</test>
<!-- Test with Firefox -->
<test name="FirefoxTest" group-by-instances="true">
<parameter name="browser" value="Firefox"></parameter>
<parameter name="browserVersion" value="43"></parameter>
<parameter name="platform" value="Windows"></parameter>
<parameter name="platformVersion" value="7"></parameter>
<classes>
<class name="Resources.TestFactory"/>
</classes>
</test>
</suite>
Data Factory Class
public class TestFactory {
#Factory(dataProvider = "LoginCredentials", dataProviderClass=TestData.class)
public Object[] createInstances(int testNo, String userName, String password) {
Object[] result = new Object[1];
int i=0;
System.out.println("Inside LoginCredentials Factory - " + userName + "---" + password);
if(testNo==1){
result[i] = new Test_BookingEngine_Login(userName, password);
i++;
System.out.println("Object Array : " + Arrays.deepToString(result));
}
else if(testNo==2){
result[i] = new Test_BookingManagement_OpenBooking(userName);
i++;
System.out.println("Object Array : " + Arrays.deepToString(result));
}
System.out.println("outside for");
return result;
}
}
Suite - Driver Initialization
#BeforeTest
#Parameters(value ={"browser", "browserVersion", "platform", "platformVersion"})
public void initBrowser(String browser, String browserVersion, String platform, String platformVersion) throws Exception{
//Initializing browser in cloud
cloudCaps = new DesiredCapabilities();
cloudCaps.setCapability("browser", browser);
cloudCaps.setCapability("browser_version", browserVersion);
cloudCaps.setCapability("os", platform);
cloudCaps.setCapability("os_version", platformVersion);
cloudCaps.setCapability("browserstack.debug", "true");
cloudCaps.setCapability("browserstack.local", "true");
driver = new RemoteWebDriver(new URL(URL), cloudCaps);
}
Sample Test
public Test_BookingEngine_Login(String userName, String password) {
this.userName = userName;
this.password = password;
}
#Test (groups = {"Login"})
public void testHomePageAppearCorrect() throws InterruptedException{
//Starting test and assigning test category
test = logger.startTest("Login to Temptation", "<b>Successful user login or Pop up advising incorrect login details</b><br/><br/>" + browserInfo)
.assignCategory("Regression", "Booking Engine")
.assignAuthor("Dinesh Cooray");
System.out.println("Inside login test");
System.out.println("Browser inside login test : ");
driver.get("http://dev-thor2.tempoholidays.com/");
test.log(LogStatus.INFO, "HTML", "Navigated to http://dev-thor2.tempoholidays.com/");
//create Login Page object
objLogin = new BookingEngine_Login(driver);
//login to application
objLogin.loginToTemptationBookingEngine(userName, password, test);
//check if alert advising username or password is is incorrect
try {
//incorrect login details, user should not allow login
if(driver.switchTo().alert().getText().toLowerCase().contains("user name or password is wrong")){
test.log(LogStatus.INFO, "HTML", "<b>Popup - </b>" + driver.switchTo().alert().getText());
driver.switchTo().alert().accept();
Assert.assertTrue(true);
}
}
I am guessing RemoteWebDriver driver; would be a line you added at the class level.
What is happening is that you have already declared the variable at class level. i.e. memory is already allocated to it.When you do something like this driver = new RemoteWebDriver(new URL(URL), cloudCaps); you are just setting and resetting the values of the same variable in every #BeforeTest
What you need to do is create a factory that will return an instance of RemoteWebDriver based on a parameter you pass to it.Essentially the factory will create a new object and return only if an existing object doesn't exist.
Declare and initialise the driver (from factory) in your #Test Methods
Sample code for the factory would be something like
static RemoteWebDriver firefoxDriver;
static RemoteWebDriver someOtherDriver;
static synchronized RemoteWebDriver getDriver(String browser, String browserVersion, String platform, String platformVersion)
{
if (browser == 'firefox')
{
if (firefoxDriver == null)
{
DesiredCapabilities cloudCaps = new DesiredCapabilities();
cloudCaps.setCapability("browser", browser);
cloudCaps.setCapability("browser_version", browserVersion);
cloudCaps.setCapability("os", platform);
cloudCaps.setCapability("os_version", platformVersion);
cloudCaps.setCapability("browserstack.debug", "true");
cloudCaps.setCapability("browserstack.local", "true");
firefoxDriver = new RemoteWebDriver(new URL(URL),cloudCaps);
}
}
else
{
if (someOtherDriver == null)
{
DesiredCapabilities cloudCaps = new DesiredCapabilities();
cloudCaps.setCapability("browser", browser);
cloudCaps.setCapability("browser_version", browserVersion);
cloudCaps.setCapability("os", platform);
cloudCaps.setCapability("os_version", platformVersion);
cloudCaps.setCapability("browserstack.debug", "true");
cloudCaps.setCapability("browserstack.local", "true");
someOtherDriver = new RemoteWebDriver(new URL(URL),cloudCaps);
}
return someOtherDriver;
}
}
}

testNG parallel execution not working

I am trying to run following test in parallel for two browsers using testNG, while running both the browsers are getting launched with the URL, but the complete test execution is happening for only one browser.
Here is my Test Suite class
#Test (groups = {"Enable"})
#SuppressWarnings("unused")
public class EETestSuite_01 extends ApplicationFunctions{
String URL = Globals.GC_EMPTY;
#BeforeTest
#Parameters("browser")
public void loadTest(String browser) throws IOException{
InitializeTestEnv("EE|BizApp");
if(browser.equalsIgnoreCase("Firefox"))
GetBrowser("Firefox");
else if(browser.equalsIgnoreCase("Chrome")){
GetBrowser("Chrome");
}
}
#AfterMethod
public void cleartest() throws InterruptedException{
driver.close();
driver.quit();
driver = null;
}
public void TC001_Phone_First_Acquisition_Journey_PAYM() throws InterruptedException{
URL = EnvDetail.get(Globals.GC_HOME_PAGE);
Map<String,String> TDChoosePlan = null;
TDChoosePlan = getData(appName+Globals.GC_TEST_DATA_SHEET,"ChoosePlan",1);
try{
launchApp(URL);
//driver.navigate().to("javascript:document.getElementById('overridelink').click()");
EEHomePage homePage = PageFactory.initElements(driver, EEHomePage.class);
EEShopPage shopPage = homePage.GetToShopPage();
EEPhoneMatrixPage phonePage = shopPage.GetToPhoneMatrixPage();
EEChoosePlanPage planPage = phonePage.ChoosePhone("NokiaLumia1020"); // Implement select phone
EEAddonsPage addonPage = planPage.SelectPhonesPlan(TDChoosePlan);
EEBasket basketPage = addonPage.GoToBasketPage();
EESecureCheckOut secureChkOutPage = basketPage.GoToSecureCheckOutPage();
secureChkOutPage.ChooseNonExistingCustomer();
EEConfirmation confPage = secureChkOutPage.FillUserRegisterForm(2);
}catch(Exception e){
e.printStackTrace();
}
}
}
My XML looks like this
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "EEAutomationTestSuite" verbose="2" parallel = "tests" thread-count="100">
<test name="PAYM Acquisition in Chrome">
<parameter name="browser" value="Firefox"></parameter>
<classes>
<class name="com.testsuite.EETestSuite_01">
</class>
</classes>
</test>
<test name="PAYM Acquisition in FF">
<parameter name="browser" value="Firefox"></parameter>
<classes>
<class name="com.testsuite.EETestSuite_01">
</class>
</classes>
</test>
</suite>
And my code for the Home page is this
*/ public EEShopPage GetToShopPage() throws InterruptedException{
// longWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(OR.getProperty("wblShopHeader"))));
lblShopHeader = driver.findElement(By.cssSelector(OR.getProperty("wblShopHeader")));
Actions builder = new Actions(driver);
Actions hoverOverRegistrar = builder.moveToElement(lblShopHeader);
hoverOverRegistrar.perform();Thread.sleep(10000);
lnkStartShopping = driver.findElement(By.cssSelector(OR.getProperty("lnkStartShopping")));
mediumWait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(OR.getProperty("lnkStartShopping"))));
lnkStartShopping.click();
return PageFactory.initElements(driver,EEShopPage.class );
}
}
Here is the driver
public static void GetBrowser(String browser){
try{
if (browser.equalsIgnoreCase("firefox")) {
// FirefoxProfile firefoxProfile = new FirefoxProfile();
// File pathToBinary = new File(Globals.GC_FIREFOX_BIN_PATH);
// FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
//firefoxProfile.setPreference("webdriver.load.strategy","unstable");
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase("iexplorer")){
System.setProperty("webdriver.ie.driver", System.getProperty("user.dir") +
"//resource//drivers//IEDriverServer.exe");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
driver = new InternetExplorerDriver(capabilities);
} else if (browser.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") +
"//resource//drivers//chromedriver.exe");
I am just guessing that there is a hover action in the home page, and for one browser it works fine but for the other nothing happens.... is it due focus issue ??
Please let me know how to solve this with an example
I cannot make it out from your code, which constructor you are using for your page Object EEHomePage.
Because, if you are using default constructor then your PageFactory will not be able to initialize your web elements unless they are defined by #FindBy annotation,
PageFactory takes webDriver and Object class as arguments and internally initializes that Object class with provided webDriver.This can be achieved by two ways as below :
1) either define your webElements in your pageObjects using #FindBy annotations as follow :
#FindBy(css=//your locator value here)
private WebElement lblShopHeader;
OR
2) define constructor and initialize your pageobject webdriver by PageFactory provided webdriver as follow :
EEHomeShop(WebDriver driver){
this.driver=driver;
}

Selenium Grid 2 parallel Test Case execution

I want to use Selenium Grid for my Testing in that I have successfully launched the Grid and Launched the HUB and NODE .. i also did set my RemoteWebdriver Capability perfectly .. but when I try run the test, all the browers is being opened perfectly but the problem i'm facing is that some browser stop in the middle like
some open the webpage and stops
some enters the login page and stops
some loges in and stop and giving me the ERROR as
Element Not Found
Unable to Click Element
Element not found in the cache
Can anyone please help me ...
Thanks in Advance.
My sample Code is
public class GmailMail{
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#BeforeClass
public void setup(String browser) throws InterruptedException, IOException {
DesiredCapabilities capability=null;
if(browser.equalsIgnoreCase("googlechrome")){
/*ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
.usingDriverExecutable(
new File("D:\\downloaded setup\\zip file\\chromedriver_win_26.0.1383.0\\chromedriver.exe"))
.usingAnyFreePort().build();
chromeDriverService.start();
driver = new ChromeDriver(chromeDriverService);*/
System.out.println("googlechrome");
capability= DesiredCapabilities.chrome();
capability.setBrowserName("chrome");
capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
//capability.setVersion("");
System.setProperty("webdriver.chrome.driver",
"D:\\downloaded setup\\zip file\\chromedriver_win_26.0.1383.0\\chromedriver.exe");
driver = new ChromeDriver();
}
if(browser.equalsIgnoreCase("firefox")){
System.out.println("firefox");
capability= DesiredCapabilities.firefox();
capability.setBrowserName("firefox");
capability.setPlatform(org.openqa.selenium.Platform.ANY);
//capability.setVersion("");
}
if(browser.equalsIgnoreCase("iexplore")){
System.out.println("iexplore");
capability= DesiredCapabilities.internetExplorer();
capability.setBrowserName("iexplore");
capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
//capability.setVersion("");*/
System.setProperty("webdriver.ie.driver", "D:\\downloaded setup\\zip file\\IEDriverServer_Win32_2.29.0\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
driver.navigate().to(baseUrl);
long ss = Thread.currentThread().getId();
System.out.println("ss: "+ss);
}
#Test
public void testUntitled() throws Exception {
driver.get(baseUrl + "/ServiceLogin?service=mail&passive=true&rm=false&continue=http://mail.google.com/mail/&scc=1&ltmpl=default&ltmplcache=2");
driver.findElement(By.id("Email")).clear();
driver.findElement(By.id("Email")).sendKeys("YourUserName");
driver.findElement(By.id("Passwd")).clear();
driver.findElement(By.id("Passwd")).sendKeys("YourPassowrd");
driver.findElement(By.id("signIn")).click();
}
#AfterClass
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
and my Testng.xml is
<suite name="Same TestCases on Different Browser" verbose="3" parallel="tests" thread-count="2">
<test name="Run on Internet Explorer">
<parameter name="browser" value="firefox"/>
<classes>
<class name="TestPAck1.GmailMail"/>
</classes>
</test>
<test name="Run on Internet Explorer1">
<classes>
<parameter name="browser" value="googlechrome"/>
<class name="TestPAck1.GmailMail"/>
</classes>
</test>
</suite>
at first glance this seems to be a sync issue. If you could share the appropriate section of your code, it might be easier to identify the issue.

Categories

Resources