How do I click on this autoComplete countryName? - java

This is the link I wanted to automate. But I am not being able to click on countryName. I wanted to enter "na" in the searchField and then click on "Nepal" using the list attribute i.e list.get(i).click() but I have not been able to. Please help
package autoComplete;
import java.time.Duration;
import java.util.List;
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.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class AutoCompleteCountry {
WebDriver driver;
String url = "https://practice-cybertekschool.herokuapp.com/autocomplete";
By countryField = By.id("myCountry");
By countryList = By.xpath("//input[#type='hidden']");
#BeforeTest
public void getUrl() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
driver.get(url);
}
#Test
public void autoCompleteTest() throws InterruptedException {
driver.findElement(countryField).sendKeys("N");
List<WebElement> listOfCountry = driver.findElements(countryList);
// driver.findElement(nepalClick).click();
for (int i = 0; i < listOfCountry.size(); i++) {
// System.out.println(list);
String searchText = listOfCountry.get(i).getAttribute("value");
System.out.println(searchText);
if (searchText.equals("Nepal")) {
listOfCountry.get(i).click();
}
}
}
#AfterTest
public void tearDown() throws InterruptedException {
Thread.sleep(5000);
driver.quit();
}
}
This is the error screenshot:
Error Screenshot

You needn't iterate through the whole list if you just want to click the "Nepal" option. Does the following help at all?
driver.findElement(By.CSS_SELECTOR, 'input[value="Nepal"]').click()

you can use Webdriver wait with a customExpected Condition like this below
Instead of using implicit wait use WebDriverwait for Fluentwait
private static ExpectedCondition<Boolean> waitForDropdownElement(By by, String value) {
return ( driver -> {
List<WebElement> listOfCountry = driver.findElements(by);
for (int i = 0; i < listOfCountry.size(); i++) {
String searchText = listOfCountry.get(i).getText();
if (searchText.equals(value)) {
listOfCountry.get(i).click();
return true;
}
}
return false;
});
}
Also modified below locator like this, as you will get element not clickable exception on using that
By countryList = By.xpath("//div[#id='myCountryautocomplete-list']//div");
Full code below which is working for me
import io.github.bonigarcia.wdm.WebDriverManager;
import java.time.Duration;
import java.util.List;
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.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class AutoCompleteCountry {
WebDriver driver;
String url = "https://practice-cybertekschool.herokuapp.com/autocomplete";
By countryField = By.id("myCountry");
By countryList = By.xpath("//div[#id='myCountryautocomplete-list']//div");
#BeforeTest
public void getUrl() {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(30));
driver.get(url);
}
#Test
public void autoCompleteTest() throws InterruptedException {
driver.findElement(countryField).sendKeys("N");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(60));
wait.until(waitForDropdownElement(countryList, "Nepal"));
}
#AfterTest
public void tearDown() throws InterruptedException {
Thread.sleep(5000);
driver.quit();
}
private static ExpectedCondition<Boolean> waitForDropdownElement(By by, String value) {
return (driver -> {
List<WebElement> listOfCountry = driver.findElements(by);
for (int i = 0; i < listOfCountry.size(); i++) {
String searchText = listOfCountry.get(i).getText();
if (searchText.equals(value)) {
listOfCountry.get(i).click();
return true;
}
}
return false;
});
}
}

Related

Selenium test in Java returns the error: Connection reset

I tried some selenium and it worked but stopped in the middle of the crawling process
these are codes:
import java.util.Date;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class Kream {
private static WebDriver driver;
public static final String WEB_DRIVER_ID = "webdriver.chrome.driver"; // 크롬 드라이버
public static final String WEB_DRIVER_PATH = "C://chromedriver.exe";
public static void main(String[] args) throws InterruptedException {
Kream krm = new Kream();
int rank = 0; // 순서 주려고 선언
System.setProperty(WEB_DRIVER_ID, WEB_DRIVER_PATH); // 운영체제 드라이버 설정
ChromeOptions options = new ChromeOptions(); // 옵션 쓰려고 객체화
options.addArguments("headless");
options.setPageLoadStrategy(PageLoadStrategy.NORMAL);
WebDriver driver = new ChromeDriver(options);
try {
String url = "https://kream.co.kr/search?category_id=34&sort=popular&per_page=40";
driver.get(url);
List<WebElement> el = driver.findElements(By.className("search_result_item"));
var stTime = new Date().getTime(); //현재시간
while (new Date().getTime() < stTime + 15000) { //30초 동안 무한스크롤 지속
Thread.sleep(500); //리소스 초과 방지
//executeScript: 해당 페이지에 JavaScript 명령을 보내는 거
((JavascriptExecutor)driver).executeScript("window.scrollTo(0, document.body.scrollHeight)", el);
for (WebElement element:el) {
System.out.println(++rank+". ");
System.out.print(element.findElement(By.tagName("img")).getAttribute("src"));
System.out.print("|"+element.findElement(By.className("brand")).getText());
System.out.print("|"+element.findElement(By.className("name")).getText());
System.out.print("|"+element.findElement(By.className("translated_name")).getText());
System.out.print("|"+element.findElement(By.className("amount")).getText());
System.out.print("|"+element.findElement(By.className("desc")).getText());
System.out.print("|"+element.findElement(By.className("express_mark")).getText());
System.out.println();
}
}
} finally {
driver.close();
driver.quit();
}
}
}
and return the error that says
onError
java.net.SocketException: Connection reset
at java.base/sun.nio.ch.SocketChannelImpl.throwConnectionReset(SocketChannelImpl.java:394)
at java.base/sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:426)
at io.netty.buffer.PooledByteBuf.setBytes(PooledByteBuf.java:258)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1132)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:357)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:151)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:722)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:658)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:584)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:833)
current versions:
chromedriver version:103.0.5060.24
chrome version: 103.0.5060.114
I already tried to match the both versions so mismatching wouldn't be the reason probably.
Thank you for the answer in advance.
I made changes to your script and this was working fine as expected, please check the below!
If still you encountered any issues, kindly share complete logs for issue resolution.
package com.selenium;
import java.util.Date;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class Kream {
private static WebDriver driver;
public static final String WEB_DRIVER_ID = "webdriver.chrome.driver"; // 크롬 드라이버
public static final String WEB_DRIVER_PATH = "C://chromedriver.exe";
public static void main(String[] args) throws InterruptedException {
Kream krm = new Kream();
int rank = 0; // 순서 주려고 선언
System.setProperty(WEB_DRIVER_ID, WEB_DRIVER_PATH); // 운영체제 드라이버 설정
ChromeOptions options = new ChromeOptions(); // 옵션 쓰려고 객체화
options.addArguments("headless");
options.setPageLoadStrategy(PageLoadStrategy.NORMAL);
WebDriver driver = new ChromeDriver();
try {
String url = "https://kream.co.kr/search?category_id=34&sort=popular&per_page=40";
driver.get(url);
List<WebElement> el = driver.findElements(By.className("search_result_item"));
var stTime = new Date().getTime(); //현재시간
while (new Date().getTime() < stTime + 15000) { //30초 동안 무한스크롤 지속
Thread.sleep(500); //리소스 초과 방지
//executeScript: 해당 페이지에 JavaScript 명령을 보내는 거
((JavascriptExecutor) driver)
.executeScript("window.scrollTo(0, document.body.scrollHeight)", el);
for (WebElement element : el) {
System.out.println(++rank + ". ");
System.out.print(element.findElement(By.tagName("img")).getAttribute("src"));
System.out.print("|" + element.findElement(By.className("brand")).getText());
System.out.print("|" + element.findElement(By.className("name")).getText());
System.out.print("|" + element.findElement(By.className("translated_name")).getText());
System.out.print("|" + element.findElement(By.className("amount")).getText());
System.out.print("|" + element.findElement(By.className("desc")).getText());
// System.out.print("|" + element.findElement(By.className("express_mark")).getText());
/*The above tag with class name as express_mark doesn't have any text attribute and hence, this is commented out!*/
System.out.println();
}
}
} finally {
driver.close();
driver.quit();
}
}
}

java.lang.NullPointerException exception is occurred when running the test script Page Object Model using Selenium Web Driver

package com.qa.base;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.qa.util.TestUitl;
public class TestBase {
public static WebDriver driver;
public static Properties prop;
// Creating a Constructor
public TestBase() {
prop = new Properties();
try {
File file = new File("/APIAutomation/CRMTest/src/main/java/com/qa/config/config.properties");
FileInputStream fis = new FileInputStream(file);
prop.load(fis);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void initializtion() {
String browser = prop.getProperty("browser");
if(browser.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "C:/APIAutomation/chromedriver.exe");
driver = new ChromeDriver();
}
else
{
System.out.println("Quit Running Script");
}
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(TestUitl.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUitl.IMPLICIT_WAIT, TimeUnit.SECONDS);
driver.get(prop.getProperty("url"));
}
}
Page Factory
package com.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.qa.base.TestBase;
public class loginPage extends TestBase{
//Page Factory
#FindBy(name="email")
WebElement email;
#FindBy(name="password")
WebElement password;
#FindBy(xpath=".//div[#class='ui fluid large blue submit button']")
WebElement loginButton;
#FindBy(xpath="//div[#class ='column']/div[2][#class='ui message']")
WebElement OldLogin;
//Initialization the Page Object
public loginPage() {
PageFactory.initElements(driver, this);
}
//Actions
public String validateLoginPageTitle() {
return driver.getTitle();
}
public String validateUserName() {
return OldLogin.getText();
}
public HomePage login(String user, String pass) {
email.sendKeys(user);
password.sendKeys(pass);
loginButton.click();
return new HomePage();
}
}
Page Factory HomePage
package com.qa.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.qa.base.TestBase;
public class HomePage extends TestBase{
//PageFactory
#FindBy(xpath = ".//div[#id='main-nav']/a[#href='/home']")
WebElement Homepage;
#FindBy(xpath =".//div/span[#class='user-display']")
WebElement username;
#FindBy(xpath =".//span[contains(text(),'Contacts')]")
WebElement contactlink;
#FindBy(xpath="//a[5][contains(#href,'/deals')]")
WebElement dealslink;
//Initializing Page Object
public HomePage() {
PageFactory.initElements(driver, this);
}
//Actions
public String validateHomePage() {
return driver.getTitle();
}
public boolean validateHomePageDisplayed() {
return Homepage.isDisplayed();
}
public String validateUser() {
return username.getText();
}
public boolean verifyUsername() {
return username.isDisplayed();
}
public ContactPage clickContactLink() {
contactlink.click();
return new ContactPage();
}
public DealsPage clickDeals() {
dealslink.click();
return new DealsPage();
}
}
Test Case Class
package com.crm.qa.TestCases;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.qa.base.TestBase;
import com.qa.pages.ContactPage;
import com.qa.pages.HomePage;
import com.qa.pages.loginPage;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
public class HomePageTest extends TestBase {
loginPage loginpage;
HomePage homepage;
ContactPage contactpage;
//Create a constructor of HomePageTest and call the super class i.e the TestBase class constructor will be called
public HomePageTest() {
super();
}
// test case should be separated - independent with each other
// before each test cases - launch the browser and login
// after each test cases - close the browser
#BeforeMethod
public void setUp() {
initializtion();
loginpage = new loginPage();
//Login method is returning homepage object
homepage = loginpage.login(prop.getProperty("username"), prop.getProperty("password"));
}
#Test
public void verifyHomePageTitleTest() {
String homepageTitle = homepage.validateHomePage();
System.out.println("Print HomePage Title:::::::::::::::::" +homepageTitle);
Assert.assertEquals(homepageTitle, "Cogmento CRM","Homepage title is not matching");
}
#Test
public void verifyUsernameTest() {
Assert.assertTrue(homepage.verifyUsername(), "Username is not matching");
}
#Test
public void verifyUserTest() {
String Username = homepage.validateUser();
Assert.assertEquals(Username, "Gokul Kuppusamy","Username text is not matching");
}
#Test
public void verifyContactPageTest() {
System.out.println("Clicking Contact Page");
contactpage = homepage.clickContactLink();
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
package com.crm.qa.TestCases;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.qa.base.TestBase;
import com.qa.pages.ContactPage;
import com.qa.pages.HomePage;
import com.qa.pages.loginPage;
public class ContactPageTest extends TestBase {
loginPage loginpage;
HomePage homepage;
ContactPage contactpage;
public ContactPageTest() {
super();
}
#BeforeMethod
public void setUp() throws Exception {
initializtion();
loginpage = new loginPage();
// Login method is returning homepage object
homepage = loginpage.login(prop.getProperty("username"), prop.getProperty("password"));
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
Thread.sleep(3000);
homepage.validateHomePageDisplayed();
/*
* Thread.sleep(3000); homepage.clickContactLink(null);
*/
}
#Test
public void verifyContactsPageNewButtonTest() {
Assert.assertTrue(contactpage.verifyNewButton());
}
#Test(priority = 1)
public void verifyContactsPageLableTest() {
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.SECONDS);
Assert.assertTrue(contactpage.verifyContactlable(), "Contacts is missing on the page");
}
#Test(priority = 2)
public void selectContactDetailsTest() {
contactpage.selectContactDetails();
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
java.lang.NullPointerException
at com.crm.qa.TestCases.ContactPageTest.verifyContactsPageNewButtonTest(ContactPageTest.java:49)
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)
initializtion();
loginpage = new loginPage();
//below line is missing please add in HomePageTest class
**homepage=new Homepage();**
Please confirm whether you are using only one driver instance for all pages, Basically Null point exception occurring for this , The solution uses a global variable for driver instance
public static Webdrivr driver;

How to call a method in every test which is in the base class and has a data provider in selenium

I have been trying to integrate browser stack with my selenium scripts. As part of which i have added desired capabilities in my 'getBrowser' method with data provider in the Base class. As i want to run my scripts in multiple browsers. The browsers list is in "getData" method in Base class.
How can i call the getBrowser method in my testcases and have the getData(browsers list) defined in only the base class. This what i have done and its not right. i have added my base class and the test script.
Base.getBrowser(Platform platform, String browserName, String browserVersion); this line is were i am stuck.
Any help would be appreciated. Thanks
package com.gale.precision.FundVisualizer.core;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.DataProvider;
import org.openqa.selenium.Platform;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Base {
//public static WebDriver driver = null;
public static WebDriver driver;
public static String DriverPath = System.getProperty("user.dir") + "//" + "Drivers";
public static String DirectoryPath = System.getProperty("user.dir");
public static Properties prop = new Properties();
public static InputStream input = null;
public static final String USERNAME = "antonyprabhu1";
public static final String AUTOMATE_KEY = "xHRMpqxgD8sn3e3sr75s";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "#hub-cloud.browserstack.com/wd/hub";
#DataProvider(name = "EnvironmentDetails")
public static void getBrowser(Platform platform, String browserName, String browserVersion) throws MalformedURLException
{
DesiredCapabilities capability = new DesiredCapabilities();
capability.setPlatform(platform);
capability.setBrowserName(browserName);
capability.setVersion(browserVersion);
capability.setCapability("browserstack.debug", "true");
driver = new RemoteWebDriver(new URL(URL), capability);
try {
input = new FileInputStream(DirectoryPath + "//" + "config" + "//" + "app.properties");
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
#DataProvider(name = "EnvironmentDetails", parallel = true)
public Object[][] getData() {
Object[][] testData = new Object[][] {
{
Platform.MAC, "chrome", "62.0"
}, {
Platform.WIN8,
"chrome",
"62.0"
}, {
Platform.WINDOWS,
"firefox",
"57"
}
};
return testData;
}
public static void closeBrowser() {
driver.quit();
}
}
package comparison;
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Platform;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.gale.precision.FundVisualizer.core.Base;
import com.gale.precision.FundVisualizer.core.ExtentReport;
import com.gale.precision.FundVisualizer.pageObject.Comparison;
import com.gale.precision.FundVisualizer.pageObject.InvestmentsSearch;
#SuppressWarnings("unused")
public class AddedInvestmentDisplay extends ExtentReport {
/*============================================================================================================================
Test case : Verify that already selected Investments for comparison does not show up
======================================================================================*/
#Test(testName = "Comparison: Verify an already selected Investment for comparison does not show up in search")
public void verifyAddedInvestmentDisplay() throws InterruptedException, MalformedURLException {
//test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName());
Base.getBrowser(Platform platform, String browserName, String browserVersion);
InvestmentsSearch.login(Base.driver);
InvestmentsSearch.InvestmentsLink(Base.driver).click();
JavascriptExecutor jse = (JavascriptExecutor) Base.driver;
jse.executeScript("window.scrollBy(0,750)", "");
InvestmentsSearch.ViewResults(Base.driver).click();
for (int i = 0; i <= 2; i++)
{
try {
Comparison.firstCheckBox(Base.driver).click();
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
//Base.clickingStaleElements(Comparison.firstCheckBox(Base.driver));
//Comparison.firstCheckBox(Base.driver).click();
for (int i = 0; i <= 2; i++)
{
try {
Comparison.analyzeOrCompare(Base.driver).click();
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Comparison.addInvestmentField(Base.driver).sendKeys("MFC027");
Comparison.firstSearchResult(Base.driver).click();
Comparison.addInvestmentField(Base.driver).sendKeys("MFC027");
Assert.assertEquals(Comparison.emptySearchResult(Base.driver).isDisplayed(), true);
}
#DataProvider(name = "EnvironmentDetails", parallel = true)
public Object[][] getData() {
Object[][] testData = new Object[][] {
{
Platform.MAC, "chrome", "62.0"
}, {
Platform.WIN8,
"chrome",
"62.0"
}, {
Platform.WINDOWS,
"firefox",
"57"
}
};
return testData;
}
#AfterClass
public void tearDown()
{
Base.closeBrowser();
}
}
I could resolve this issue by passing the parameters in the #test method
#Test(testName="Comparison: Verify adding an index in the comparison", dataProvider = "EnvironmentDetails",dataProviderClass = BrowsersDataProvider.class)
public void verifyAddingIndex(Platform platform, String browserName, String browserVersion) throws InterruptedException, MalformedURLException {
//test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName());
Base.getBrowser(platform,browserName,browserVersion);
InvestmentsSearch.login(Base.driver);
like

When i am trying to run the code then an error message is occur

When i am trying to run below mention code the an error message is occur. In my code i am trying to execute logout function. for this logout function, i have prepared a excel where logout xpath properly store. but when i am trying to execute this code an error message is occur.error message is Element is not clickable at point (1155, 20). Other element would receive the click
package com.rmspl.multiplemethod;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class MethodSet {
static WebElement element;
public void login (String username,String password,String nr,WebDriver fd) {
fd.get("http://117.247.65.9/vms_test");
fd.manage().window().maximize();
WebElement E1 = fd.findElement(By.name("j_username"));
E1.sendKeys(username);
WebElement E2 = fd.findElement(By.name("j_password"));
E2.sendKeys(password);
WebElement E3 = fd.findElement(By.name("log"));
E3.click();
}
public void clickLink(String xPath,String nr,String nr1,WebDriver fd){
element = fd.findElement(By.xpath(xPath));
element.click();
}
public void Select(String xPath,String val,String nr1,WebDriver fd){
Select sel = new Select(fd.findElement(By.xpath(xPath)));
sel.selectByValue(val);
}
}
package com.rmspl.multiplemethod;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestDriver {
static WebElement element;
public static void main(String[] args) throws BiffException, IOException, NoSuchMethodException, SecurityException,
IllegalAccessException,IllegalArgumentException, InvocationTargetException {
MethodSet mt = new MethodSet();
System.setProperty("webdriver.chrome.driver","C:\\Users\\Arijit Mohanty\\Desktop\\chromedriver.exe");
WebDriver fd = new ChromeDriver();
FileInputStream fis = new FileInputStream("C:\\Users\\Arijit Mohanty\\Desktop\\Bangla\\HybridDatasheet.xls");
Workbook WB = Workbook.getWorkbook(fis);
Sheet Sh = WB.getSheet("Sheet2");
int rows = Sh.getRows();
int cols = Sh.getColumns();
for (int i = 1; i<rows; i++)
{
String methodname = Sh.getCell(0, i).getContents();
String data1 = Sh.getCell(1, i).getContents();
String data2 = Sh.getCell(2, i).getContents();
String data3 = Sh.getCell(3, i).getContents();
Method m1 = mt.getClass().getMethod(methodname, String.class,String.class,String.class, WebDriver.class);
m1.invoke(mt,data1,data2,data3,fd);
}
}
}
You need to wait for loading_bg till goes off the screen. please update the method clickLink as given below. please try and let us know.
public void clickLink(String xPath,String nr,String nr1,WebDriver fd){
new WebDriverWait(fd, 90).until(ExpectedConditions.invisibilityOfElementLocated(By.id("loading_bg")));
element = fd.findElement(By.xpath(xPath));
element.click();
}

Selenium null pointer exception, when trying to use constructor

I created a class which has page objects defined in it. Then I am trying to use that class in a test class by using a constructor. However when I run the test class using JUnit I am getting a NullPointerException error.
Page_Objects Class:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.Select;
public class Page_Objects {
private WebDriver driver;
WebElement Username = driver.findElement(By.id("username"));
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
WebElement Password = driver.findElement(By.id("password"));
WebElement Login_Button = driver.findElement(By.id("Login"));
WebElement Logout_Button = driver.findElement(By.linkText("Logout"));
}
Test Class:
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Salesforce_Test {
private WebDriver driver1;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
Page_Objects pageobjects = new Page_Objects();
#Before
public void setUp() throws Exception {
driver1 = new FirefoxDriver();
baseUrl = "some url for testing/";
driver1.navigate().to(baseUrl);
driver1.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void Login_Logout() throws Exception {
pageobjects.Username.sendKeys("someusername");
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
pageobjects.Password.sendKeys("somepassword");
pageobjects.Login_Button.click();
pageobjects.Logout_Button.click();
}
#After
public void tearDown() throws Exception {
driver1.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver1.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver1.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver1.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
When I run the above class I get a null pointer exception.
java.lang.NullPointerException
at Page_Objects.<init>(Page_Objects.java:20)
at Salesforce_Test.<init>(Salesforce_Test.java:16)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
I see two issues here. First is that the Page_Objects class is called before you initiated the driver. That's why when you're calling
Page_Objects pageobjects = new Page_Objects();
you're getting a NullPointerException.
So you want to initiate the Page_Objects after you've initiated the driver.
Second, you need to pass it the instance of the driver you've initiated, because right now it has its own Private driver which isn't initiated and therefore it's null.
So in short:
Initiate Page_Objects after you've initiated driver (after the driver1 = new FirefoxDriver(); line)
Call it with the driver you've initiated: Page_Objects pageobjects = new Page_Objects(driver1 );

Categories

Resources