I am unable to find what is the cause of the error "org.openqa.selenium.WebDriverException" in my code, Please help me find and understand the cause much better. Firstly I would like to explain my code, It is a simple code where I go to a website click on "Sign In" link and then click on a text "Email" text field for registration purpose. I have used Page Factory in this code.
I have 3 files.
- Base file (Before and After methods)
- Registration File (Object repository and methods)
- Registration_Testcase File (Calling the methods)
Note: Base and Registration Testcase classes are in one package and Registration is in another package.
**Below is my code:**
Base Class
package testcases;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
public class Base {
public WebDriver driver;
public WebDriverWait wait;
#BeforeTest
public void beforeTest() {
ProfilesIni pro = new ProfilesIni();
FirefoxProfile ffProfile = pro.getProfile("vishvesh");
ffProfile.setAcceptUntrustedCertificates(true);
ffProfile.setAssumeUntrustedCertificateIssuer(false);
String base_url = "http://automationpractice.com/index.php";
System.setProperty("webdriver.gecko.driver", "G:/Workplace/AutomationSetupFiles/Geckdriver/geckodriver.exe");
driver = new FirefoxDriver();
driver.get(base_url);
}
#AfterTest
public void afterTest() {
driver.close();
}
}
Registration Class
package pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import testcases.Base;
public class Registration extends Base{
#FindBy(xpath="//*[#id='header']/div[2]//div[1]/a")
WebElement SignIn;
#FindBy(xpath="//input[#id='email_create']")
WebElement Registration_Email;
public Registration(WebDriver driver){
this.driver=driver;
PageFactory.initElements(driver, this);
}
public void ClickSignIn(){
//wait.until(ExpectedConditions.visibilityOf(SignIn)).click();
SignIn.click();
}
public void EnterEmail(String y){
//wait.until(ExpectedConditions.visibilityOf(Registration_Email)).click();
Registration_Email.click();
Registration_Email.sendKeys(y);
}
}
Registration TestCase Class
package testcases;
import org.testng.annotations.Test;
import pages.Registration;
public class Registatration_testcase extends Base{
#Test
public void f() {
Registration regobj = new Registration(driver);
regobj.ClickSignIn();
regobj.EnterEmail("amdv1991#gmail.com");
}
}
Error What I get:
FAILED CONFIGURATION:
#BeforeTest beforeTest
org.openqa.selenium.WebDriverException:
Build info: version: 'unknown', revision: '8c03df6', time: '2017-03-02 09:32:39 -0800'
System info: host: 'LAPTOP-SCJ4OHK5', ip: '192.168.1.3', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{moz:profile=C:\Users\VISHVE~1\AppData\Local\Temp\rust_mozprofile.XaA5YbSD8jeh, rotatable=false, timeouts={implicit=0, pageLoad=300000, script=30000}, pageLoadStrategy=normal, platform=ANY, specificationLevel=0, moz:accessibilityChecks=false, acceptInsecureCerts=false, browserVersion=53.0.3, platformVersion=10.0, moz:processID=7440, browserName=firefox, platformName=windows_nt}]
Session ID: 1ad0b6c1-bb5c-4306-afa6-b4e3dcb62ac1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:127)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:93)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:42)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:163)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:604)
at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:325)
at testcases.Base.beforeTest(Base.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:108)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:523)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:224)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:146)
at org.testng.TestRunner.beforeRun(TestRunner.java:626)
at org.testng.TestRunner.run(TestRunner.java:594)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)
I have seemed to have resolved this issue, Looked like there was some compatibility issues. Now I am using the following configurations
selenium 3.4
Firefox browser v48
geckodriver 17
Related
I'm using selenium 4 and trying to locate some elements (Username and password credentials) "Username : Admin
Password : admin123" using Relative Locators selenium 4 new feature but the Code throws org.openqa.selenium.NoSuchElementException: Cannot locate an element using [unknown locator] but when I debugged the code to test it, it passed successfully ,found the elements and printed the values on the console. anyone has a proposed solution?
org.openqa.selenium.NoSuchElementException: Cannot locate an element using \[unknown locator\]
For documentation on this error, please visit: https://selenium.dev/exceptions/#no_such_element
Build info: version: '4.4.0', revision: 'e5c75ed026a'
System info: host: 'DESKTOP-M0R33E6', ip: '192.168.1.4', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '13.0.2'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.By.findElement(By.java:124)
at org.openqa.selenium.remote.ElementLocation$ElementFinder$1.findElement(ElementLocation.java:136)
at org.openqa.selenium.remote.ElementLocation.findElement(ElementLocation.java:80)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:365)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:357)
at OrangeHrm.Pages.LoginPage.getUsernameUsingRelativeLocator(LoginPage.java:29)
at OrangeHrm_Tests.Login.LoginTests.test_GetUserCredentials(LoginTests.java:10)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.testng.internal.invokers.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:135)
at org.testng.internal.invokers.TestInvoker.invokeMethod(TestInvoker.java:673)
at org.testng.internal.invokers.TestInvoker.invokeTestMethod(TestInvoker.java:220)
at org.testng.internal.invokers.MethodRunner.runInSequence(MethodRunner.java:50)
at org.testng.internal.invokers.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:945)
at org.testng.internal.invokers.TestInvoker.invokeTestMethods(TestInvoker.java:193)
at org.testng.internal.invokers.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.invokers.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
at org.testng.TestRunner.privateRun(TestRunner.java:808)
at org.testng.TestRunner.run(TestRunner.java:603)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:429)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:423)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:383)
at org.testng.SuiteRunner.run(SuiteRunner.java:326)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:95)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1249)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1169)
at org.testng.TestNG.runSuites(TestNG.java:1092)
at org.testng.TestNG.run(TestNG.java:1060)
at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:109)
Website URL: https://opensource-demo.orangehrmlive.com/web/index.php/auth/login
LoginPage.java
package OrangeHrm.Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.locators.RelativeLocator;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginPage {
private WebDriver driver;
private By loginPageTitle = By.tagName("h5");
WebElement usernameCredential;
WebElement passwordCredential;
public LoginPage(WebDriver driver){
this.driver = driver;
}
public String getUsernameUsingRelativeLocator(){
usernameCredential = driver.findElement(RelativeLocator.with(By.xpath("//div[contains(#class , 'oxd-sheet--rounded')]/p[1]"))
.below(loginPageTitle));
System.out.println(usernameCredential.getText());
return usernameCredential.getText();
}
public String getPasswordUsingRelativeLocator(){
passwordCredential = driver.findElement(RelativeLocator.with(By.xpath("//div[contains(#class , 'oxd-sheet--rounded')]/p[2]"))
.below(username));
System.out.println(passwordCredential.getText());
return passwordCredential.getText();
}
}
OrangeHrmWebTestBase.java
package OrangeHrm_Tests.Base;
import OrangeHrm.Pages.LoginPage;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.time.Duration;
public class OrangeHrmWebTestBase {
private WebDriver driver;
protected LoginPage loginPageObj;
#BeforeClass
public void setUp(){
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://opensource-demo.orangehrmlive.com/");
loginPageObj = new LoginPage(driver);
}
#AfterClass
public void teatDown(){
driver.quit();
}
}
LoginTests.java
package OrangeHrm_Tests.Login;
import OrangeHrm_Tests.Base.OrangeHrmWebTestBase;
import org.testng.annotations.Test;
public class LoginTests extends OrangeHrmWebTestBase {
#Test
public void test_GetUserCredentials(){
loginPageObj.getUsernameUsingRelativeLocator();
loginPageObj.getPasswordUsingRelativeLocator();
}
}
You seem to be pretty close using Below as a Relative Locator within the OrangeHRM website.
However instead of using the <div> with the text Username : Admin and Password : admin123 as Relative Locators you can use the <label> with text as Username and Password.
Code Block:
package AwesomeDay;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.locators.RelativeLocator;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class RelativeLocators2 {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
//WebElement userNameLabel = driver.findElement(By.xpath("//label[text()='Username']"));
WebElement userNameLabel = new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[text()='Username']")));
By userName = RelativeLocator.with(By.tagName("input")).below(userNameLabel);
driver.findElement(userName).sendKeys("Ali");
WebElement passwordLabel = driver.findElement(By.xpath("//label[text()='Password']"));
By password = RelativeLocator.with(By.tagName("input")).below(passwordLabel);
driver.findElement(password).sendKeys("Eleish");
}
}
Browser Snapshot:
I am making a maven project and at the time of opening the chrome browser is shows
java.lang.NullPointerException exeption, i am unable to find what is missing here and why browser is not opening.
my base class is like this
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterMethod;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import pages.LandingPage;
import pages.LoginPage;
import utils.ExtentReportManager;
import utils.DateUtils;
public class Base {
public WebDriver driver;
public Properties prop;
public ExtentReports report = ExtentReportManager.getReportInstance();
public ExtentTest logger;
public void invokeBrowser(String browsername) {
try {
if (browsername.equalsIgnoreCase("Chrome")) {
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir") + "\\src\\resourc\\driver\\chromedriver.exe");
driver = new ChromeDriver();//This is line 39 in Base
} else if (browsername.equalsIgnoreCase("Firefox")) {
System.setProperty("webdriver.gecko.driver",
System.getProperty("user.dir") + "\\src\\resourc\\driver\\geckodriver.exe");
driver = new FirefoxDriver();
} else {
System.setProperty("webdriver.IEDriverServer.driver",
System.getProperty("user.dir") + "\\src\\resourc\\driver\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
} catch (Exception e) {
e.printStackTrace();
}
driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);//**This is line 53**
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(180, TimeUnit.SECONDS);
prop = new Properties();
try {
FileInputStream file = new FileInputStream(
System.getProperty("user.dir") + "\\src\\resourc\\ObjectRepository\\projectConfig.properties");
prop.load(file);
} catch (Exception e) {
e.printStackTrace();
}
}
public LandingPage OpenApplication(String websiteURLKey ) {
driver.get(prop.getProperty(websiteURLKey));
return PageFactory.initElements(driver, LandingPage.class);
}
public void closebrowser() {
driver.close();
}
#AfterMethod
public void reportFlush() {
report.flush();
}
/****************** Capture Screen Shot ***********************/
public void takeScreenShotOnFailure() {
TakesScreenshot takeScreenShot = (TakesScreenshot) driver;
File sourceFile = takeScreenShot.getScreenshotAs(OutputType.FILE);
File destFile = new File(System.getProperty("user.dir") + "/ScreenShots/" + DateUtils.getTimeStamp() + ".png");
try {
FileUtils.copyFile(sourceFile, destFile);
// logger.addScreenCaptureFromPath(
// System.getProperty("user.dir") + "/ScreenShots/" + DateUtils.getTimeStamp() + ".png");
} catch (IOException e) {
e.printStackTrace();
}
}
}
and my test class is like this from where i am running all the files for project one by one
package test;
import org.apache.http.client.utils.DateUtils;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import base.Base;
import pages.DisplayDetails;
import pages.HomePage;
import pages.LandingPage;
import pages.LoginPage;
import pages.UpcomingBikesPage;
import utils.ExtentReportManager;
public class ProjectTest extends Base{
LandingPage landingpage;
LoginPage loginpage;
HomePage homepage;
UpcomingBikesPage upcomingbikespage;
DisplayDetails displaydetails;
#Test
public void openBrowser() throws Exception {
logger = report.createTest("Zigwheels Website Automation");
Base base = new Base();
logger.log(Status.INFO, "Initializing the Browser");
base.invokeBrowser("chrome");//**This is line 32 in test file**
logger.log(Status.INFO, "Opening the Website");
landingpage = base.OpenApplication("websiteURL");
logger.log(Status.INFO, " Login initated Successfully");
loginpage = landingpage.initiatelogin();
logger.log(Status.INFO, "Entered Credentials Successfully");
homepage = loginpage.login();
logger.log(Status.INFO, "Login Successfull");
upcomingbikespage = homepage.home();
logger.log(Status.INFO, "Got Upcoming Honda Bikes Successfully");
displaydetails=upcomingbikespage.hondamanufacturer();
displaydetails.finaly();
//logger.addScreenCaptureFromPath(System.getProperty("user.dir") + "/ScreenShots/" + DateUtils.getTimeStamp() + ".png");
}
}
And in the console Error is as follows--
[RemoteTestNG] detected TestNG version 6.14.3
Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987#{#882}) on port 36324
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
FAILED: openBrowser
java.lang.NullPointerException
at base.Base.invokeBrowser(Base.java:53)
at test.ProjectTest.openBrowser(ProjectTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Line 53 is Shown through comment that is implicit wait line
Line 32 in test is also shown through comment that is base.invokeBrowser("chrome"); line.
org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 80
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'PRANJAL', ip: '192.168.225.26', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_241'
Driver info: driver.version: ChromeDriver
remote stacktrace: Backtrace:
Ordinal0 [0x00F80C83+1707139]
Ordinal0 [0x00EE68F1+1075441]
Ordinal0 [0x00E5DFC9+516041]
Ordinal0 [0x00DF0554+66900]
Ordinal0 [0x00DECCE2+52450]
Ordinal0 [0x00E0BFD7+180183]
Ordinal0 [0x00E0BDDD+179677]
Ordinal0 [0x00E09D4B+171339]
Ordinal0 [0x00DF1D4A+73034]
Ordinal0 [0x00DF2DC0+77248]
Ordinal0 [0x00DF2D59+77145]
Ordinal0 [0x00EFBB67+1162087]
GetHandleVerifier [0x0101A966+508998]
GetHandleVerifier [0x0101A6A4+508292]
GetHandleVerifier [0x0102F7B7+594583]
GetHandleVerifier [0x0101B1D6+511158]
Ordinal0 [0x00EF402C+1130540]
Ordinal0 [0x00EFD4CB+1168587]
Ordinal0 [0x00EFD633+1168947]
Ordinal0 [0x00F15B35+1268533]
BaseThreadInitThunk [0x75F9343D+18]
RtlInitializeExceptionChain [0x77209812+99]
RtlInitializeExceptionChain [0x772097E5+54]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$errorHandler$0(W3CHandshakeResponse.java:62)
at org.openqa.selenium.remote.HandshakeResponse.lambda$getResponseFunction$0(HandshakeResponse.java:30)
at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:126)
at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
I've built your code. It works fine; it runs passed that line.
I've used my own chromedriver absolute path.
Might be a typo somewhere for your path. I suggest using pwd in a terminal/powershell in that chromedriver directory.
If not, it's potentially a missing selenium library. Have you downloaded selenium libraries and manually imported them?
if (browsername.equalsIgnoreCase("Chrome")) {
System.setProperty("webdriver.chrome.driver",
"/Users/user/Documents/qac-cv-management-system/AutomatedTestReact/chromedriver");
driver = new ChromeDriver();//This is line 39 in
}
Hi Everyone I was trying to make a Selenium Script to verify the validations on Username and Password Text Box by fetching the data from Excel file (.xlt format) but whenever i am running my code it is getting the following error after successful loop run . The code is as follows :
package com.selenium.com.selenium.practise;
import org.testng.annotations.Test;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.testng.annotations.BeforeMethod;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
public class MultipleCasesUsingExcel {
public static WebDriver driver = null;
#Test
public void Test() throws BiffException, IOException, InterruptedException {
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// Clicking on My Account Link
driver.findElement(By.xpath("//*[#id='top']/body/div/div/div[3]/div/div[4]/ul/li[1]/a")).click();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebElement emailTextBox = driver.findElement(By.xpath("//input[#id='email']"));
WebElement pwdTextBox = driver.findElement(By.xpath("//input[#id='pass']"));
WebElement loginBtn = driver.findElement(By.xpath("//button[#id='send2']"));
Workbook book = Workbook.getWorkbook(new File("C:\\Users\\Umang Bhatia\\Documents\\data.xlt"));
Sheet sheet = book.getSheet(0);
for (int i = 0; i < sheet.getRows(); i++) {
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
for (int j = 0; j < sheet.getColumns() - 1; j++) {
emailTextBox.sendKeys(sheet.getCell(j, i).getContents());
pwdTextBox.sendKeys(sheet.getCell(j + 1, i).getContents());
loginBtn.click();
emailTextBox.clear();
pwdTextBox.clear();
}
Thread.sleep(3000);
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#BeforeMethod
public void beforeMethod() {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Umang Bhatia\\Documents\\Selenium Drivers\\chrome driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://live.guru99.com/index.php/");
}
#AfterMethod
public void afterMethod() {
driver.quit();
}
}
And I am getting the following error after first successful loop run :
[RemoteTestNG] detected TestNG version 6.13.1
Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 36887
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
FAILED: Test
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=63.0.3239.132)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.10586 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 31 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'DESKTOP-59DNS54', ip: '192.168.2.5', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\UMANGB~1\AppData\Local\Temp\scoped_dir13984_1984}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=63.0.3239.132, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, setWindowRect=true, unexpectedAlertBehaviour=}]
Session ID: eb78d1ac176166bdaa86da5dc12e09c0
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:326)
at org.openqa.selenium.remote.RemoteWebElement.clear(RemoteWebElement.java:139)
at com.selenium.com.selenium.practise.MultipleCasesUsingExcel.Test(MultipleCasesUsingExcel.java:55)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:571)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:707)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:979)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1116)
at org.testng.TestNG.runSuites(TestNG.java:1028)
at org.testng.TestNG.run(TestNG.java:996)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================
Could any one Explain why I am getting this error and how it can be fixed
That's because you change page in your test, thus your element references break. Have a look at WebDriverExtensions. This framework provides method on opening your links in new windows without invalidating references of WebElements, and enables dynamic lookup of your elements.
Alternatively, if you don't want to use this framework, you could re-search for your elements in your loop like this:
//...
for (int j = 0; j < sheet.getColumns() - 1; j++) {
// add these lines
emailTextBox = driver.findElement(By.xpath("//input[#id='email']"));
pwdTextBox = driver.findElement(By.xpath("//input[#id='pass']"));
loginBtn = driver.findElement(By.xpath("//button[#id='send2']"));
// clear inputs before login. After you click loginBtn, the page
// changes, and references of WebElements are invalidated,
// thus your emailTextBox.clear(); methods threw anexception
emailTextBox.clear();
pwdTextBox.clear();
emailTextBox.sendKeys(sheet.getCell(j, i).getContents());
pwdTextBox.sendKeys(sheet.getCell(j + 1, i).getContents());
loginBtn.click();
}
I use TestNG + Selenium + Appium.
Problem which i have is:
If the 1st #Test fails, all rest got failed automatically and execution will be stopped.
I tried to use #BecoreClass setUp instead of setting up at #Test still after first failure fails everything.
I thought that it skipping all the rest of the test because of it does not finish the process in the right way ( quitting an application ) that`s why i added #Aftermethod with driver.quit that it will execute it after failed method.
But still after 1st failure it automatically Fails all the tests.
I need to have multiple #Test with a test methods, which will be individual with separate configurations. And if 1st one fails, it will continue execute the rest of #Test ( even if they are from the same class) and after will give me a result .
package foundation;
import com.pageobjects.HeaderMenu;
import config.AppConfiguration;
import config.LogIn;
import config.DesiredCapabilitiesSetup;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.pagefactory.AppiumFieldDecorator;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.*;
import org.testng.asserts.SoftAssert;
import java.io.IOException;
public class AppiumTestTest {
private AndroidDriver<AndroidElement> driver;
private AOWebClient aoWeb;
#SuppressWarnings("unused")
public AppiumTestTest(AndroidDriver<AndroidElement> driver, AOWebClient aoWeb) {
this.driver = driver;
this.aoWeb = aoWeb;
PageFactory.initElements(new AppiumFieldDecorator(driver), this);
}
#SuppressWarnings("unused")
public AppiumTestTest() {
}
private SoftAssert softAssert = new SoftAssert();
/*
#BeforeClass
public void setUp() throws Exception {
}
*/
#Test
public void checkInTest() throws Exception {
driver = DesiredCapabilitiesSetup.startAppiumServer(
AppConfiguration.newBuilder()
.setTimeSelection(false)
.setBirthday(true)
.build());
AOWebClient aoWebClient = DesiredCapabilitiesSetup.getAOWeb();
LogIn logIn = new LogIn(driver, aoWebClient);
logIn.logIn();
}
#Test
public void timeSelectionTest() throws Exception {
driver = DesiredCapabilitiesSetup.startAppiumServer(
AppConfiguration.newBuilder()
.setTimeSelection(true)
.setBirthday(true)
.build());
AOWebClient aoWebClient = DesiredCapabilitiesSetup.getAOWeb();
LogIn logIn = new LogIn(driver, aoWebClient);
logIn.logIn();
}
#AfterMethod
public void afterM(){
driver.close();
driver.quit();
}
}
My Desired Capabilities are:
package config;
import com.pageobjects.LaunchProgress;
import com.sun.javafx.tools.ant.DeployFXTask;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.remote.MobilePlatform;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.json.simple.JSONObject;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeClass;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
public class DesiredCapabilitiesSetup {
//Name of Android Device
//public static String deviceName = "TestDevice";
// Emulator
//public static String deviceName = "One";
//Path of App folder
// public static String appLink = "/Users/af185125/FoundationApp/";
//The name of Android application with format. (.apk).
//public static String appName = "app331.apk";
private static final String KEY_USE_TIME_SELECTION = "useTimeSelection";
private static final String KEY_DISABLE_BIRTHDAY = "disableBirthday";
#BeforeClass
public static AndroidDriver<AndroidElement> startAppiumServer(AppConfiguration appConfiguration) throws IOException {
// Taking App/Device/Link path from *txt file located in the project //
/*
String appLink = FileUtils.readFileToString(new File("appConfigurations/appLink.txt"));
String deviceName = FileUtils.readFileToString(new File("appConfigurations/deviceName.txt"));
String appName = FileUtils.readFileToString(new File("appConfigurations/appName.txt"));
*/
String appLink = FileUtils.readFileToString(new File("appConfigurations/appLink.txt"));
String deviceName = FileUtils.readFileToString(new File("appConfigurations/deviceName.txt"));
String appName = FileUtils.readFileToString(new File("appConfigurations/appName.txt"));
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID);
cap.setCapability(MobileCapabilityType.DEVICE_NAME, deviceName);
cap.setCapability(MobileCapabilityType.VERSION, "6.0");
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, "4000");
String configurationString = getConfigurationString(appConfiguration);
cap.setCapability(AndroidMobileCapabilityType.OPTIONAL_INTENT_ARGUMENTS,"--es appium_config \"" + configurationString + "\"");
//cap.setCapability("avd","nexus");
File appSource = new File(appLink);
File app = new File(appSource, appName);
cap.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
AndroidDriver<AndroidElement> driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap);
driver.manage().timeouts().implicitlyWait(80, TimeUnit.SECONDS);
LaunchProgress launch = new LaunchProgress(driver);
launch.waitForLaunchScreenToLoad();
return driver;
}
#SuppressWarnings("unchecked")
private static String getConfigurationString(AppConfiguration appConfiguration) {
JSONObject configuration = new JSONObject();
configuration.put(KEY_USE_TIME_SELECTION, appConfiguration.timeSelection);
configuration.put(KEY_DISABLE_BIRTHDAY, appConfiguration.birthday);
return configuration.toJSONString();
}
}
Stacktrace:
objc[20683]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home/bin/java and /Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home/jre/lib/libinstrument.dylib. One of the two will be used. Which one is undefined.
Connected to the target VM, address: '127.0.0.1:58385', transport: 'socket'
[TestNG] Running:
/Users/af185125/Library/Caches/IdeaIC2016.2/temp-testng-customsuite.xml
org.openqa.selenium.NoSuchElementException: An element could not be located on the page using the given search parameters. (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 80.28 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.1', revision: 'a36b8b1cd5757287168e54b817830adce9b0158d', time: '2016-06-30 19:26:09'
System info: host: 'WUSAF185125-G3D', ip: '153.86.242.30', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_91'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities [{app=/Users/af185125/android-ui-test/currentApp/appiumT.apk, appPackage=com.ao.demo.beta, networkConnectionEnabled=true, warnings={}, appWaitPackage=com.ao.demo.beta, appWaitActivity=com.ao.core.ui.launch.LaunchActivity, databaseEnabled=false, deviceName=ad071603280ea0c18d, version=6.0, fullReset=true, platform=LINUX, deviceUDID=ad071603280ea0c18d, appActivity=com.ao.core.ui.launch.LaunchActivity, desired={app=/Users/af185125/android-ui-test/currentApp/appiumT.apk, newCommandTimeout=4000, platformVersion=6.0, automationName=Appium, platformName=Android, deviceName=Automation, version=6.0, optionalIntentArguments=--es appium_config "{"useTimeSelection":false,"disableBirthday":true}", fullReset=true}, newCommandTimeout=4000, platformVersion=6.0.1, webStorageEnabled=false, locationContextEnabled=false, automationName=Appium, takesScreenshot=true, javascriptEnabled=true, platformName=Android, optionalIntentArguments=--es appium_config "{"useTimeSelection":false,"disableBirthday":true}"}]
Session ID: 30270d0f-8594-4ead-b5b6-56dfeee37f44
*** Element info: {Using=id, value=fasf.com}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:51)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:67)
at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:413)
at io.appium.java_client.DefaultGenericMobileDriver.findElementById(DefaultGenericMobileDriver.java:75)
at io.appium.java_client.AppiumDriver.findElementById(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.findElementById(AndroidDriver.java:1)
at org.openqa.selenium.By$ById.findElement(By.java:218)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
at io.appium.java_client.DefaultGenericMobileDriver.findElement(DefaultGenericMobileDriver.java:63)
at io.appium.java_client.AppiumDriver.findElement(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.findElement(AndroidDriver.java:1)
at foundation.AppiumTestTest.checkInTest(AppiumTestTest.java:61)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:100)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:646)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:811)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1129)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:746)
at org.testng.TestRunner.run(TestRunner.java:600)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1264)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1189)
at org.testng.TestNG.runSuites(TestNG.java:1104)
at org.testng.TestNG.run(TestNG.java:1076)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:124)
org.openqa.selenium.WebDriverException: Method has not yet been implemented (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 7 milliseconds
Build info: version: '2.53.1', revision: 'a36b8b1cd5757287168e54b817830adce9b0158d', time: '2016-06-30 19:26:09'
System info: host: 'WUSAF185125-G3D', ip: '153.86.242.30', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_91'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities [{app=/Users/af185125/android-ui-test/currentApp/appiumT.apk, appPackage=com.ao.demo.beta, networkConnectionEnabled=true, warnings={}, appWaitPackage=com.ao.demo.beta, appWaitActivity=com.ao.core.ui.launch.LaunchActivity, databaseEnabled=false, deviceName=ad071603280ea0c18d, version=6.0, fullReset=true, platform=LINUX, deviceUDID=ad071603280ea0c18d, appActivity=com.ao.core.ui.launch.LaunchActivity, desired={app=/Users/af185125/android-ui-test/currentApp/appiumT.apk, newCommandTimeout=4000, platformVersion=6.0, automationName=Appium, platformName=Android, deviceName=Automation, version=6.0, optionalIntentArguments=--es appium_config "{"useTimeSelection":false,"disableBirthday":true}", fullReset=true}, newCommandTimeout=4000, platformVersion=6.0.1, webStorageEnabled=false, locationContextEnabled=false, automationName=Appium, takesScreenshot=true, javascriptEnabled=true, platformName=Android, optionalIntentArguments=--es appium_config "{"useTimeSelection":false,"disableBirthday":true}"}]
Session ID: 30270d0f-8594-4ead-b5b6-56dfeee37f44
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:51)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:268)
at org.openqa.selenium.remote.RemoteWebDriver.close(RemoteWebDriver.java:521)
at foundation.AppiumTestTest.afterM(AppiumTestTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:100)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:515)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:216)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:712)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:811)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1129)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:746)
at org.testng.TestRunner.run(TestRunner.java:600)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1264)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1189)
at org.testng.TestNG.runSuites(TestNG.java:1104)
at org.testng.TestNG.run(TestNG.java:1076)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:124)
Test ignored.
org.openqa.selenium.WebDriverException: Method has not yet been implemented (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 5 milliseconds
Build info: version: '2.53.1', revision: 'a36b8b1cd5757287168e54b817830adce9b0158d', time: '2016-06-30 19:26:09'
System info: host: 'WUSAF185125-G3D', ip: '153.86.242.30', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_91'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities [{app=/Users/af185125/android-ui-test/currentApp/appiumT.apk, appPackage=com.ao.demo.beta, networkConnectionEnabled=true, warnings={}, appWaitPackage=com.ao.demo.beta, appWaitActivity=com.ao.core.ui.launch.LaunchActivity, databaseEnabled=false, deviceName=ad071603280ea0c18d, version=6.0, fullReset=true, platform=LINUX, deviceUDID=ad071603280ea0c18d, appActivity=com.ao.core.ui.launch.LaunchActivity, desired={app=/Users/af185125/android-ui-test/currentApp/appiumT.apk, newCommandTimeout=4000, platformVersion=6.0, automationName=Appium, platformName=Android, deviceName=Automation, version=6.0, optionalIntentArguments=--es appium_config "{"useTimeSelection":false,"disableBirthday":true}", fullReset=true}, newCommandTimeout=4000, platformVersion=6.0.1, webStorageEnabled=false, locationContextEnabled=false, automationName=Appium, takesScreenshot=true, javascriptEnabled=true, platformName=Android, optionalIntentArguments=--es appium_config "{"useTimeSelection":false,"disableBirthday":true}"}]
Session ID: 30270d0f-8594-4ead-b5b6-56dfeee37f44
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:51)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:268)
at org.openqa.selenium.remote.RemoteWebDriver.close(RemoteWebDriver.java:521)
at foundation.AppiumTestTest.afterM(AppiumTestTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:100)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:515)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:216)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:712)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:811)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1129)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:746)
at org.testng.TestRunner.run(TestRunner.java:600)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1264)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1189)
at org.testng.TestNG.runSuites(TestNG.java:1104)
at org.testng.TestNG.run(TestNG.java:1076)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:124)
Move driver = DesiredCapabilitiesSetup.startAppiumServer... to #BeforeMethod. Also if you want to use different drivers for tests you will have to add parametrization (e.g. #BeforeMethod for group, #DataProvider or #Facotry).
In my code, I wanted to do, so that if the test takes more than 10 seconds, the selenium shows the title of the window and closes the window. This code is here:
import java.io.File;
import java.util.Timer;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.os.WindowsUtils;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SanDemoSearch{
public static long czasStart;
public static void main(String[] args) {
czasStart = System.currentTimeMillis();
System.out.println(czasStart);
File file = new File("C:/automatyzacja/IEDriverServer_Win32_2.44.0/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.get("https://www.google.pl/?gws_rd=ssl");
Narzedzia.disableScreenSaver(driver);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.id("lst-ib")));
driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ENTER);
(new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
WebElement webElement = driver.findElement(By.xpath("//a[#href='http://www.seleniumhq.org/']"));
Assert.assertNotNull("Not found http://www.seleniumhq.org//",webElement);
webElement.click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.findElement(By.id("q")).sendKeys("test",Keys.ENTER);
}
}
and:
import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.util.Timer;
import java.util.TimerTask;
import org.openqa.selenium.WebDriver;
public class Narzedzia extends SanDemoSearch{
private static Timer screenSaverDisabler;
public static void disableScreenSaver(final WebDriver driver){
screenSaverDisabler = new Timer();
screenSaverDisabler.scheduleAtFixedRate(new TimerTask() {
Robot r = null;
{
try {
r = new Robot();
} catch (AWTException headlessEnvironmentException) {
screenSaverDisabler.cancel();
}
}
#Override
public void run() {
Point loc = MouseInfo.getPointerInfo().getLocation();
r.mouseMove(loc.x + 1, loc.y);
r.mouseMove(loc.x, loc.y);
long czasEnd = System.currentTimeMillis();
System.out.println(czasEnd);
long difference = (czasEnd - SanDemoSearch.czasStart) / 1000;
System.out.println("difference"+difference);
if(difference > 10){
System.out.println("I can quit application");
driver.getTitle(); //exception: Error 404: Not Found
driver.close();
}
//if()
}
}, 0, 1*1000);
}
}
When I run this code I got error:
Exception in thread "Timer-0" org.openqa.selenium.UnsupportedCommandException: Error 404: Not Found
Not Found
Command duration or timeout: 49 milliseconds
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:03:00'
System info: host: 'SFL000361', ip: '192.168.1.103', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_40'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{browserAttachTimeout=0, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.usePerProcessProxy=false, ignoreZoomSetting=false, handlesAlerts=true, version=10, platform=WINDOWS, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, browserName=internet explorer, initialBrowserUrl=http://localhost:32854/, takesScreenshot=true, javascriptEnabled=true, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=dismiss}]
Session ID: 959f1633-48b4-4bb6-b24d-21a919747655
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:614)
at org.openqa.selenium.remote.RemoteWebDriver.getTitle(RemoteWebDriver.java:313)
at Narzedzia$1.run(Narzedzia.java:35)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
and not always I got error:
Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: session 4b141e0f-b680-4094-92f7-efaa6ea32e75 does not exist
Command duration or timeout: 9 milliseconds
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:03:00'
System info: host: 'SFL000361', ip: '192.168.1.103', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_40'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{browserAttachTimeout=0, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.usePerProcessProxy=false, ignoreZoomSetting=false, handlesAlerts=true, version=10, platform=WINDOWS, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, browserName=internet explorer, initialBrowserUrl=http://localhost:28022/, takesScreenshot=true, javascriptEnabled=true, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=dismiss}]
Session ID: 4b141e0f-b680-4094-92f7-efaa6ea32e75
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:162)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
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 SanDemoSearch.main(SanDemoSearch.java:48)
Problem is with line: driver.getTitle. Selenium didn't see driver?
Follow this link: https://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_Is_WebDriver_thread-safe?
Q: Is WebDriver thread-safe?
A: WebDriver is not thread-safe. Having said that, if you can
serialise access to the underlying driver instance, you can share a
reference in more than one thread. This is not advisable. You /can/ on
the other hand instantiate one WebDriver instance for each thread.
Your code schedules a task using Timer object. Timer class uses another (background) thread to execute it's tasks - it means that two threads are trying to access the same WebDriver instance at the same time.
You can't use the same driver instance among two threads at the same time, because WebDriver is not thread-safe.
Use this code in java
:-
private static final ThreadLocal < WebDriver > webDriver = new ThreadLocal < WebDriver > () {
#Override protected WebDriver initialValue() {
return webdriver.instance;
}
};