Getting null pointer in dataprovider using excel? - selenium

I am trying to read data from excel file and pass it to web page form using data driven framework, In my framework I am having baseclass and in which I am invoking browser instance and then destroying it by using custom methods and Further I have a seprate module named "excelutility" which contains two java files the first one is called "excelSetup" to define all methods such method to read data from cells, to find total rows and columns the class code is given below:-
public class ExcelSetup {
FileInputStream fis;
XSSFWorkbook wb;
XSSFSheet sheet;
CellType type;
XSSFCell cell;
public ExcelSetup(String excelPath, int sheetIndex){
try{
fis=new FileInputStream(excelPath);
wb= new XSSFWorkbook(fis);
sheet=wb.getSheetAt(sheetIndex);
}catch (IOException e){
System.out.println("The error message is "+e.getMessage());
System.out.println("The cause of error is "+e.getCause());
e.getStackTrace();
}
}
public int getcolumncount(){
int colcount=0;
try{
colcount=sheet.getRow(0).getLastCellNum();
System.out.println("The total number of columns are "+colcount);
}catch (Exception e){
System.out.println("The error message is "+e.getMessage());
System.out.println("The cause of error is "+e.getCause());
e.getStackTrace();
}
return colcount;
}
public int getRowcount() {
int rowCount=0;
try {
rowCount=sheet.getPhysicalNumberOfRows();
System.out.println("The total number of rows are "+rowCount);
}catch (Exception e){
System.out.println("The error message is "+e.getMessage());
System.out.println("The cause of error is "+e.getCause());
e.getStackTrace();
}
return rowCount;
}
public String getCellData(int rowNo, int colNo){
String strdata = null;
Double data=0.0;
cell=sheet.getRow(rowNo).getCell(colNo);
type=cell.getCellType();
if (type==CellType.STRING){
strdata=cell.getStringCellValue();
}
else if (type==CellType.NUMERIC){
cell.setCellType(CellType.STRING);
strdata=cell.getStringCellValue();
}
return strdata;
}
}
The other class is named as "excelDataprovider" which is used to create and setup dataprovider which can be used to supply data in testclass
The code is given below:-
public class ExcelDataprovider {
#DataProvider(name = "namedata")
public Object[][] createnameData(){
String sheetpath=System.getProperty("user.dir")+"/configurations/data.xlsx";
Object data[][]=getData(sheetpath,0);
return data;
}
public Object[][] getData(String excelPath,int sheetindex){
ExcelSetup obj=new ExcelSetup(excelPath,sheetindex);
int rowCount=obj.getRowcount();
int colCount=obj.getcolumncount();
Object[][]data=new Object[rowCount][colCount];
for (int i = 1; i <rowCount ; i++) {
for (int j = 0; j <colCount ; j++) {
String cellData=obj.getCellData(i,j);
System.out.print(cellData+" | ");
data[i-1][j]=cellData;
}
System.out.println(" ");
}
return data;
}
}
The class where dataprovider is used is testclass whose code is given below:-
public class VerifyRegisterpage {
String title="Register: Mercury Tours";
#Test(dataProviderClass = ExcelDataprovider.class,dataProvider =
"namedata",priority=1,description="This test will submit by entering name")
public void checknamesubmit(String firstname,String lastname) throws
IOException
{
WebDriver driver=PagefactoryBase.startbrowser();
Registration register=PageFactory.initElements(driver,
Registration.class);
register.clickregisterlink();
register.checkregisterpagetitle(title);
register.checkregisterpageimage();
register.submitbyentername(firstname,lastname);
}
}
The problem is that I am able to read one set or row of data written in the excel but after reading one row It reads an empty row and supply null value to dataprovider as a result I am getting nullpointerexception.The console output is:-
The total number of rows are 2
The total number of columns are 2
srikant | chaturvedi |
Browser Instance Created
Starting ChromeDriver 2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7) on port 39207
Only local connections are allowed.
Dec 02, 2018 10:47:16 PM org.openqa.selenium.remote.ProtocolHandshake createSession
Chrome driver instance initialized
INFO: Detected dialect: OSS
INFO 2018-12-02 22:47:21,191 Registration.java [main] com.pageobjects.Registration:55 - Registration page title checked
INFO 2018-12-02 22:47:21,231 Registration.java [main] com.pageobjects.Registration:63 - Register page image has been validated
INFO 2018-12-02 22:47:26,961 Registration.java [main] com.pageobjects.Registration:108 - Registration URL has been validated successfully
INFO 2018-12-02 22:47:26,961 Registration.java [main] com.pageobjects.Registration:79 - submit by entering name is done
INFO 2018-12-02 22:47:28,565 Registration.java [main] com.pageobjects.Registration:55 - Registration page title checked
INFO 2018-12-02 22:47:28,605 Registration.java [main] com.pageobjects.Registration:63 - Register page image has been validated
org.openqa.selenium.WebDriverException: unknown error: keys should be a string
(Session info: chrome=70.0.3538.110)
(Driver info: chromedriver=2.37.544315 (730aa6a5fdba159ac9f4c1e8cbc59bf1b5ce12b7),platform=Windows NT 10.0.17134 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
Build info: version: '3.10.0', revision: '176b4a9', time: '2018-03-02T19:03:16.397Z'
System info: host: 'KESHAVPC', ip: '192.168.228.2', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_144'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.37.544315 (730aa6a5fdba15..., userDataDir: C:\Users\HP\AppData\Local\T...}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 70.0.3538.110, webStorageEnabled: true}
Session ID: 307437e89f8c3d905d650384f734db4c
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:214)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:160)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:279)
at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:100)
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.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:51)
at com.sun.proxy.$Proxy8.sendKeys(Unknown Source)
at com.pageobjects.Registration.Entername(Registration.java:116)
at com.pageobjects.Registration.submitbyentername(Registration.java:75)
at com.register.VerifyRegisterpage.checknamesubmit(VerifyRegisterpage.java:36)
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:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:580)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:716)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:988)
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.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
===============================================
Default Suite
Total tests run: 2, Failures: 1, Skips: 0
===============================================
Please refer screenshot of project structure
Please refer screenshot of excel sheet data
Please refer screenshot of null data value

You have a prob in initializing object[][] instance .Change this
Object[][]data=new Object[rowCount][colCount];
to
Object[][]data=new Object[rowCount-1][colCount];

Related

Not able to select drop-down value in Selenium

I am trying to select a value for State and City field in https://demoqa.com/automation-practice-form form. When I try to access the state field it's throwing an error no such element: Unable to locate element.
Below are the following code snippet and the error message.
//State
new WebDriverWait(driver , 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='react-select-3-input']"))).sendKeys("NCR");
new WebDriverWait(driver ,20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(#class,'css-2613qy-menu')]"))).click();
//City
new WebDriverWait(driver , 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='react-select-4-input']"))).sendKeys("Noida");
new WebDriverWait(driver ,20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(#class,'css-2613qy-menu')]"))).click();
Error
Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for element to be clickable: By.xpath: //div[contains(#class,'css-2613qy-menu')] (tried for 20 second(s) with 500 milliseconds interval)
at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:95)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:272)
at newpackage.Example.main(Example.java:117)
Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[contains(#class,'css-2613qy-menu')]"}
(Session info: chrome=84.0.4147.105)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'DESKTOP-E926NDJ', ip: '192.168.178.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_181'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 84.0.4147.105, chrome: {chromedriverVersion: 84.0.4147.30 (48b3e868b4cc0..., userDataDir: C:\Users\hp\AppData\Local\T...}, goog:chromeOptions: {debuggerAddress: localhost:54539}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:virtualAuthenticators: true}
Session ID: c4cdf6fd8a060246b9284b9e4be7ccf7
*** Element info: {Using=xpath, value=//div[contains(#class,'css-2613qy-menu')]}
at sun.reflect.GeneratedConstructorAccessor10.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:187)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:428)
at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:205)
at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:201)
at org.openqa.selenium.support.ui.ExpectedConditions$22.apply(ExpectedConditions.java:641)
at org.openqa.selenium.support.ui.ExpectedConditions$22.apply(ExpectedConditions.java:638)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:249)
... 1 more
Also suggest for the code to select the city field.
The element you are trying to click is in different div.
Use xpath in code snippet below.
Alternatively you can also use class name as well
//State
new WebDriverWait(driver , 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='react-select-3-input']"))).sendKeys("NCR");
new WebDriverWait(driver ,20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(#id,'react-select')]"))).click();
//City
new WebDriverWait(driver , 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='react-select-4-input']"))).sendKeys("Noida");
new WebDriverWait(driver ,20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(#id,'react-select')]"))).click();
thanks for the code to select "State" and "City", this is really helpful. I too did some minor changes in code and following code also works.
WebElement e1 = dr.findElement(By.xpath("//input[#id='react-select-3-input']"));
e1.sendKeys("Uttar Pradesh");
e1.sendKeys(Keys.ENTER);
WebElement e2 = dr.findElement(By.xpath("//input[#id='react-select-4-input']"));
e2.sendKeys("Lucknow");
e2.sendKeys(Keys.ENTER);
You can use the below code snippet to click on State and City and select appropriate value from drop down:
// To Click State drop down
driver.findElement(By.id("state")).click();
WebDriverWait wait1 = new WebDriverWait(driver, 10);
WebElement element1 = wait1
.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='react-select-3-input']")));
element1.sendKeys("NCR");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
// To Click City drop down
driver.findElement(By.id("city")).click();
WebDriverWait wait2 = new WebDriverWait(driver, 10);
WebElement element2 = wait2
.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='react-select-4-input']")));
element2.sendKeys("Delhi");
Robot robot1 = new Robot();
robot1.keyPress(KeyEvent.VK_ENTER);
robot1.keyRelease(KeyEvent.VK_ENTER);
Sometimes, I too feel the same, I will use java script executor to handles such kind of Web-elements.

Not able to do Sendkeys() in Username box. It shows Elementnotinteractable Exception using Selenium Webdriver

In Registration Form, Trying to enter text in username text box using sendkeys(). But it throws ElementNotInteractable Exception. Then i used implicit wait and webdriverwait to find that element , it also throwed be Timeout Exception. Kindly suggest a solutions for this, as i am not able to proceed for here. Used selenium Webdriver with java.
here is the site used
Attached the DOM tree image
Code Below:
#Test
public void regform() {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
RemoteWebDriver d = new ChromeDriver();
d.manage().window().maximize();
d.get("http://way2automation.com/way2auto_jquery/index.php");
d.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebDriverWait wait = new WebDriverWait(d, 20);
WebElement usrname = d.findElementByXPath("//input[#name='username']");
wait.until(ExpectedConditions.visibilityOf(usrname));
usrname.sendKeys("User1");
d.close();
}
Console Log:
FAILED: regform
org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of [[ChromeDriver: chrome on WINDOWS (12e645803db8e870be7722d06896cc88)] -> xpath: //input[#name='username']] (tried for 20 second(s) with 500 milliseconds interval)
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-O0V8JPK', ip: '192.168.1.12', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_171'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 81.0.4044.138, chrome: {chromedriverVersion: 80.0.3987.106 (f68069574609..., userDataDir: C:\Users\Shamili\AppData\Lo...}, goog:chromeOptions: {debuggerAddress: localhost:61086}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 12e645803db8e870be7722d06896cc88
at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:95)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:272)
at basicautomationconcepts.RegistrationForm.regform(RegistrationForm.java:24)
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:133)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:584)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:172)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:804)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:145)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.testng.TestRunner.privateRun(TestRunner.java:770)
at org.testng.TestRunner.run(TestRunner.java:591)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:402)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:396)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:355)
at org.testng.SuiteRunner.run(SuiteRunner.java:304)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
at org.testng.TestNG.runSuites(TestNG.java:1032)
at org.testng.TestNG.run(TestNG.java:1000)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
The page you try to automate contains two similar forms, hence there are two elements within the DOM that match your XPath. The first one is not displayed and thus not interactable. That is why you got ElementNotInteractableException, and that is why you get TimeoutException trying to wait until it became visible.
Changing your xpath to "(//input[#name='username'])[2]" should solve the problem.
You can also try with the below xpath. It worked for me.
"//*[#id=\"load_form\"]/fieldset[6]/input"

Is InvalidArgumentException ensureCleanSession a known IEDriverServer 3.12.0 issue or am I instantiating it incorrectly?

When I attempt to instantiate IEDriverServer 3.12.0 like this:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class StartInternetExplorer {
public static void main(String[] args) {
// Add to Windows PATH variable: C:\IEDriverServer_Win32_3.12.0\;
String executable = "C:\\IEDriverServer_Win32_3.12.0\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", executable);
WebDriver driver = new InternetExplorerDriver();
driver.get("https://www.google.com");
driver.quit();
}
}
I see this exception stack trace:
Started InternetExplorerDriver server (32-bit)
3.12.0.0
Listening on port 46039
Only local connections are allowed
Exception in thread "main" org.openqa.selenium.InvalidArgumentException: All firstMatch elements failed validation
Invalid capabilities in firstMatch element 0: unknown capability named ensureCleanSession
Build info: version: '3.12.0', revision: '7c6e0b3', time: '2018-05-08T14:04:26.12Z'
System info: host: 'XXXXXXXX', ip: '127.0.0.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_161'
Driver info: driver.version: InternetExplorerDriver
remote stacktrace:
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.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:123)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:126)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:545)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:209)
at org.openqa.selenium.ie.InternetExplorerDriver.run(InternetExplorerDriver.java:223)
at org.openqa.selenium.ie.InternetExplorerDriver.<init>(InternetExplorerDriver.java:215)
at org.openqa.selenium.ie.InternetExplorerDriver.<init>(InternetExplorerDriver.java:152)
at app.StartInternetExplorer.main(StartInternetExplorer.java:11)
I don't know where the "ensureCleanSession" argument is coming from, so I don't know if this means there is a bug in 3.12.0 or if I am not instantiating IEDriverServer properly.
Tried passing 4 slashes in URL and it worked. Seems they have make some changes in selenium API but I am not sure. This worked for me:
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Money {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World");
System.setProperty("webdriver.ie.driver", "IEDriverServer.exe");
InternetExplorerDriver driver=new InternetExplorerDriver();
driver.get("https:\\\\www.google.com");
}
}
I cannot replicate this in release 3.14.0 - The solution was to wait for a new release.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class StartInternetExplorer {
public static void main(String[] args) {
// Add to Windows PATH variable: C:\IEDriverServer_Win32_3.14.0\;
String executable = "C:\\IEDriverServer_Win32_3.14.0\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver", executable);
WebDriver driver = new InternetExplorerDriver();
driver.get("https://www.google.com");
driver.quit();
}
}

Getting java.lang.NullPointerException while finding a table with Selenium Webdriver

I am new to Selenium Webdriver. I am getting Null Pointer exception while trying to find the rows present in the table. Can anyone please help me to resolve this? Please find the below scenario and code that I am using for this.
URL: http://newtours.demoaut.com/
Scenario: To click on each link that present in the table present in the left hand side of the page. Just under Mercury Tours image.
Here is code that I am using,
public class HomePage {
private WebDriver driver = null;
public HomePage(WebDriver driver){
this.driver = driver;
}
public void VerifyTableLink() throws InterruptedException{
List<WebElement> rowObj = driver.findElements(By.xpath("//td[p[img[#alt='Mercury Tours']]]/table/tbody/tr"));
System.out.println("testttt");
for(int i=0;i<rowObj.size();i++){
WebElement we = driver.findElement(By.xpath("//td[p[img[#alt='Mercury Tours']]]/table/tbody/tr["+i+"]/td[2]/a"));
we.click();
Thread.sleep(5);
driver.navigate().back();
String text = we.getText();
System.out.println(text);
}
}
}
public class VerifyNavigationTable {
WebDriver driver = null;
#Parameters({"bname","appurl"})
#BeforeMethod
public void preCondition(#Optional("Chrome")String brow, #Optional("http://newtours.demoaut.com/")String url){
driver = BrowserSelection.getBrowser(brow);
BrowserSelection.openURL(url);
}
#Test
public void verifyTableLink() throws InterruptedException{
HomePage hp = new HomePage(driver);
hp.VerifyTableLink();
}
}
Exception Message:
[Utils] Directory D:\My Selenium Training\Practical\SeleniumLearning\SeleniumPractice4\test-output\Default suite exists: true
FAILED: verifyTableLink
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//td[p[img[#alt='Mercury Tours']]]/table/tbody/tr[0]/td[2]/a"}
(Session info: chrome=54.0.2840.99)
(Driver info: chromedriver=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf),platform=Windows NT 6.2.9200 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10.07 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: 'unknown', revision: '1969d75', time: '2016-10-18 09:43:45 -0700'
System info: host: 'Bishnu', ip: '192.168.0.107', os.name: 'Windows 8', os.arch: 'amd64', os.version: '6.2', java.version: '1.8.0_111'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf), userDataDir=C:\Users\Bishnu\AppData\Local\Temp\scoped_dir10480_1335}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=54.0.2840.99, platform=WIN8, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: c1401a5ed7966a2f15d6570c612b2449
*** Element info: {Using=xpath, value=//td[p[img[#alt='Mercury Tours']]]/table/tbody/tr[0]/td[2]/a}
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:216)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:635)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:368)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:473)
at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:360)
at in.prolearn.newtours.pages.HomePage.VerifyTableLink(HomePage.java:20)
at in.prolearn.newtours.testcases.VerifyNavigationTable.verifyTableLink(VerifyNavigationTable.java:26)
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: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:1137)
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:753)
at org.testng.TestRunner.run(TestRunner.java:607)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:368)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:363)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:321)
at org.testng.SuiteRunner.run(SuiteRunner.java:270)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1284)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1209)
at org.testng.TestNG.runSuites(TestNG.java:1124)
at org.testng.TestNG.run(TestNG.java:1096)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
Any suggestion will help me to understand the tool in better way.
Thanks
To find each row of the table you can use this xpath: //tr[#class='mouseOut']
Since you are interested only on links("a" nodes), I suggest to write your code like this:
List<WebElement> linksInTable = driver.findElements(By.xpath("//tr[#class='mouseOut']//a"));
for(WebElement a : linksInTable){
// write what you want to do with each link
}
You might also encounter a problem because you are using "back" in your codes. Probably(you should test it to become sure) you should find web elements again each time you back to the main page. Something similar to:
for(int i=0;i<linksInTable.size();i++) {
String text = linksInTable[i].getText();
System.out.println(text);
linksInTable[i].click();
driver.navigate().back();
linksInTable = driver.findElements(By.xpath("//tr[#class='mouseOut']//a"));
}

softassert not being called.. Only getting NoSuchElementException

In one my testcase I am trying to find whether an element is displayed after login.
softAssert.assertTrue(landing1PageFuncs.getSetupBtn().isDisplayed(), "Login Failed");
softAssert.assertAll();
getSetupBtn getter method is as below
public WebElement getSetupBtn() {
return AppWait.waitForElement(driver, setupBtn , Constants.WAITTIME);
}
waitForElement function is as below
public static WebElement waitForElement(WebDriver driver, WebElement element, int timeOutInSeconds) {
try {
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
element = wait.until(ExpectedConditions.visibilityOf(element));
driver.manage().timeouts().implicitlyWait(DEFAULT_WAIT_4_ELEMENT, TimeUnit.SECONDS); //reset implicitlyWait
} catch (Exception e) {
logger.warn(element + " not found even after waiting for: " + timeOutInSeconds + " seconds");
logger.warn(e, new RuntimeException());
}
return element;
}
But what I am observing is that isDisplayed method is never invoked. Hence the soft assertion is not being fired.
All I get is the exception as below:
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//*[#id='page_content_inner']/div/a[1]/div"}
Command duration or timeout: 19 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '2.53.0', revision: '35ae25b1534ae328c771e0856c93e187490ca824', time: '2016-03-15 10:43:46'
System info: host: 'justdial', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '3.13.0-86-generic', java.version: '1.8.0_91'
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=46.0.1, platform=LINUX, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: 6b9e0607-ee41-42b8-bb58-0f7d6cc32481
*** Element info: {Using=xpath, value=//*[#id='page_content_inner']/div/a[1]/div}
at sun.reflect.GeneratedConstructorAccessor13.newInstance(Unknown Source)
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 org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.openqa.selenium.support.events.EventFiringWebDriver$2.invoke(EventFiringWebDriver.java:103)
at com.sun.proxy.$Proxy9.findElement(Unknown Source)
at org.openqa.selenium.support.events.EventFiringWebDriver.findElement(EventFiringWebDriver.java:188)
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy11.isDisplayed(Unknown Source)
at org.justdial.jdomni.functionaltests.LoginPageTests.chkLoginWithValidCred(LoginPageTests.java:38)
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:86)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:643)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1128)
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:782)
at org.testng.TestRunner.run(TestRunner.java:632)
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:1244)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1169)
at org.testng.TestNG.run(TestNG.java:1064)
at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:74)
What I am doing wrong? I am looking for a solution which goes till the Assertion and says "Login Failed"
Any help appreciated.
Your element cannot be found, so isDisplayed() cannot be determined. isDisplayed() can only be called on an element that exists and has already been found, that is why your assertion is never called.
landing1PageFuncs.getSetupBtn() throws an exception before isDisplayed() is being called.
If you want to find out if an element exists on the page, you should use driver.findElements(By.xpath('locator')).size > 0 instead of driver.findElement(By.xpath('locator').isDisplayed()
Since the element is not available in DOM, u cannot apply a soft assertion and obviously u'll get NoSuchElementException.
you can write a utility method like below to verify the whether the locator exists or not in the DOM.
public class verifyloc {
public static void main(String a[]) {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
String loc = "//input[#id='lst-ib']";
By locator = verifyElementPresent(driver, loc);
System.out.println("Locator is : " + locator);
}
public static By verifyElementPresent(WebDriver driver, String locator) {
try {
driver.findElement(By.xpath(locator));
return By.xpath(locator);
} catch (Throwable e) {
return null;
}
}
}