The code in the "basePageNavigation" #Test is running fine on the first data set, but when the method is ran the second time, the first line in it:
driver.get(prop.getProperty("url"));
is ignored, and thus the test fails on the first findElement method called. When I run this in debug mode having a breakpoint at that line, it works fine. Code:
package Academy;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import pageObjects.ForgotPassword;
import pageObjects.Landingpage;
import pageObjects.Loginpage;
import resources.base;
public class Homepage extends base{
public static Logger log = LogManager.getLogger(Homepage.class.getName());
public WebDriver driver;
#BeforeTest
public void initialize() throws IOException
{
driver=initializeDriver();
log.info("Driver initialized");
}
#Test(dataProvider="getData")
public void basePageNavigation(String username, String password, String text) throws IOException
{
driver.get(prop.getProperty("url"));
Landingpage l=new Landingpage(driver);
Loginpage lp = l.getLogin();
lp.getEmail().sendKeys(username);
lp.getPassword().sendKeys(password);
lp.getLoginBtn().click();
ForgotPassword fp = lp.forgotPassword();
fp.getEmail().sendKeys("test");
fp.nextButton().click();
}
#DataProvider
public Object[][] getData()
{
//Row (first value) stands for how many different data types the test will run
//Column (second value) stands for how many values are parsed per test
Object[][] data = new Object[2][3];
// First row
data[0][0] = "nonResabc#qa.com";
data[0][1] = "12345";
data[0][2] = "Non Restricted User";
//Second Row
data[1][0] = "Resabc#qa.com";
data[1][1] = "34567";
data[1][2] = "Restricted User";
return data;
}
#AfterTest
public void tearDown()
{
driver.close();
}
}
Related
I am getting java.lang.NullPointerException while following Page Object Model with Cucumber. I am not sure what I am doing wrong here, please help me on this
Below is my Test Base Class:
package com.qa.util;
import java.io.FileInputStream;
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 org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class TestBase {
public static WebDriver driver;
public static Properties prop;
//public WebDriver initializeWebDriver() throws IOException
public static void initializeWebDriver() throws IOException
{
prop = new Properties();
FileInputStream fis = new FileInputStream("D:\\Automation\\WebAutomation\\src\\main\\java\\com\\qa\\config\\config.properties");
prop.load(fis);
String browserName = prop.getProperty("browser");
//Execute in Chrome
if(browserName.equals("Chrome"))
{
System.setProperty("webdriver.chrome.driver","D:\\Drivers\\chromedriver.exe");
driver=new ChromeDriver();
//driver.manage().window().maximize();
}
//Execute in FireFox
else if(browserName.equals("Firefox"))
{
System.setProperty("webdriver.gecko.driver","D:\\Drivers\\geckodriver-v0.19.1-win64(1)");
driver = new FirefoxDriver();
}
driver.manage().window().maximize();
driver.get(prop.getProperty("appURL"));
driver.manage().timeouts().pageLoadTimeout(TestUtil.PAGE_LOAD_TIMEOUT,TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(TestUtil.IMPLICIT_WAIT, TimeUnit.SECONDS);
return driver;
}
}
Below is my login page Objects Class
package com.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.qa.util.TestBase;
public class LoginPage extends TestBase {
public LoginPage() {
/*super(driver);
this.driver=driver;*/
PageFactory.initElements(driver, this);
}
// Login Page Title
public String validateLoginPageTitle() {
return driver.getTitle();
}
// Welcome text
#FindBy(css=".login-form > h2:nth-child(1)")
WebElement header;
public String loginPageHeaderText() {
return header.getText();
}
}
Below is my Step Def
package com.qa.stepdefinations;
import java.io.IOException;
import org.testng.Assert;
import com.qa.pages.LoginPage;
import com.qa.util.TestBase;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class LoginStepDef extends TestBase {
LoginPage LoginPage = new LoginPage();
#Given("^I launch browser and access the GE URL$")
public void i_launch_browser() throws IOException {
TestBase.initializeWebDriver();
}
#Then("^I am on Login Page$")
public void i_am_on_login_page() {
String expectedLoginPageTile = prop.getProperty("LoginPage_Title");
String actualLoginPageTitle = LoginPage.validateLoginPageTitle();
Assert.assertEquals(actualLoginPageTitle, expectedLoginPageTile);
}
#Then("^I verify header text is displaying$")
public void i_verify_header_text_is_displaying() {
String expectedHeaderText = prop.getProperty("LoginPage_Expected_Header");
String actualdHeaderText = LoginPage.loginPageHeaderText();
Assert.assertEquals(actualdHeaderText, expectedHeaderText);
}
}
The script is working fine for LoginPage.validateLoginPageTitle(); however, I am not sure why it is not working for the next step i.e. LoginPage.loginPageHeaderText();
It seems issue is with your locator, check if it is correct.
#FindBy(css="<b><em>.login-form > h2:nth-child(1)</em></b>")
WebElement header;
Goal: I have a class called "InvokeChromeTest" I'm extending to another class called "Base" to access chromedriver and data.properties. When running my code, I get the error:
Error:(22, 3) java: missing return statement
I am unsure how to fix this. Here is my sample code as follows. Please let me know what I can do to fix.
src/test/java/loginPage/InvokeChromeTest
package loginPage;
import credentials.ProfileCredentials;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import resources.Base;
public class InvokeChromeTest extends Base {
#Test
public WebDriver initializeDriver() {
driver = initializeDriver();
driver.get(dataProperties.getProperty("url"));
ProfileCredentials p = new ProfileCredentials(driver);
p.getAuthorize().click();
p.getApiKey().sendKeys("testKey");
p.getAuthCred().click();
p.getCloseAuth().click();
}
#AfterTest
public void teardown() {
driver.close();
}
}
src/main/java/resources/Base
package resources;
import io.github.bonigarcia.wdm.WebDriverManager;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Base {
public WebDriver driver;
protected Properties dataProperties;
public WebDriver initializeDriver() {
// Create global property file
dataProperties = new Properties();
InputStream dataPropertiesInputStream = null;
try{
dataPropertiesInputStream = getClass().getClassLoader().getResourceAsStream("data.properties");
dataProperties.load(dataPropertiesInputStream);
} catch (IOException e) {
e.printStackTrace();
}
String browserName = dataProperties.getProperty("browser");
System.out.println(browserName);
if (browserName.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if (browserName.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
src/main/java/credentials/ProfileCredentials
package credentials;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class ProfileCredentials {
WebDriver driver;
public ProfileCredentials(WebDriver driver) {
this.driver = driver;
}
private By authorize = By.xpath("//button[#class='btn authorize unlocked']");
private By apikey = By.xpath("//div[#class='wrapper']//section//input");
private By authorizecred = By.xpath("//button[#class='btn modal-btn auth authorize button']");
private By closeauth = By.xpath("//button[#class='btn modal-btn auth btn-done button']");
public WebElement getAuthorize() {
return driver.findElement(authorize);
}
public WebElement getApiKey() {
return driver.findElement(apikey);
}
public WebElement getAuthCred() {
return driver.findElement(authorizecred);
}
public WebElement getCloseAuth() {
return driver.findElement(closeauth);
}
}
I figured out the problem. "Base" and "InvokeChromeTest" had the same method name. This is why it was recursive.
I am trying to get data from a webpage (http://steamcommunity.com/id/Winning117/games/?tab=all) using a specific tag but I keep getting null. My desired result is to get the "hours played" for a specific game - Cluckles' Adventure in this case.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class TestScrape {
public static void main(String[] args) throws Exception {
String url = "http://steamcommunity.com/id/Winning117/games/?tab=all";
Document document = Jsoup.connect(url).get();
Element playTime = document.select("div#game_605250").first();
System.out.println(playTime);
}
}
Edit: How can I tell if a webpage is using JavaScript and is therefore unable to be parsed by Jsoup?
To execute javascript in java code there is Selenium :
Selenium-WebDriver makes direct calls to the browser using each
browser’s native support for automation.
To include it with maven use this dependency:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.4.0</version>
</dependency>
Next I give you code of simple JUnit test that creates instance of WebDriver and goes to given url and executes simple script to get rgGames .
File chromedriver you have to download at https://sites.google.com/a/chromium.org/chromedriver/downloads.
package SeleniumProject.selenium;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import junit.framework.TestCase;
#RunWith(JUnit4.class)
public class ChromeTest extends TestCase {
private static ChromeDriverService service;
private WebDriver driver;
#BeforeClass
public static void createAndStartService() {
service = new ChromeDriverService.Builder()
.usingDriverExecutable(new File("D:\\Downloads\\chromedriver_win32\\chromedriver.exe"))
.withVerbose(false).usingAnyFreePort().build();
try {
service.start();
} catch (IOException e) {
System.out.println("service didn't start");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#AfterClass
public static void createAndStopService() {
service.stop();
}
#Before
public void createDriver() {
ChromeOptions chromeOptions = new ChromeOptions();
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
driver = new RemoteWebDriver(service.getUrl(), capabilities);
}
#After
public void quitDriver() {
driver.quit();
}
#Test
public void testJS() {
JavascriptExecutor js = (JavascriptExecutor) driver;
// Load a new web page in the current browser window.
driver.get("http://steamcommunity.com/id/Winning117/games/?tab=all");
// Executes JavaScript in the context of the currently selected frame or
// window.
ArrayList<Map> list = (ArrayList<Map>) js.executeScript("return rgGames;");
// Map represent properties for one game
for (Map map : list) {
for (Object key : map.keySet()) {
// take each key to find key "name" and compare its vale to
// Cluckles' Adventure
if (key instanceof String && key.equals("name") && map.get(key).equals("Cluckles' Adventure")) {
// print all properties for game Cluckles' Adventure
map.forEach((key1, value) -> {
System.out.println(key1 + " : " + value);
});
}
}
}
}
}
As you can see selenium loads page at
driver.get("http://steamcommunity.com/id/Winning117/games/?tab=all");
And to get data of all games by Winning117 it returns rgGames variable:
ArrayList<Map> list = (ArrayList<Map>) js.executeScript("return rgGames;");
The page you want to scrape is load by js,and there is not any #game_605250 element that jsoup get.All datas are write in page by using js.
But when I print document to a file ,I see some data like this:
<script language="javascript">
var rgGames = [{"appid":224260,"name":"No More Room in Hell","logo":"http:\/\/cdn.steamstatic.com.8686c.com\/steamcommunity\/public\/images\/apps\/224260\/670e9aba35dc53a6eb2bc686d302d357a4939489.jpg","friendlyURL":224260,"availStatLinks":{"achievements":true,"global_achievements":true,"stats":false,"leaderboards":false,"global_leaderboards":false},"hours_forever":"515","last_played":1492042097},{"appid":241540,"name":"State of Decay","logo":"http:\/\/....
then,you can extract 'rgGames' by some StringTools and format it to json obj.
It't not a clerver method,but it worked
try this :
public class TestScrape {
public static void main(String[] args) throws Exception {
String url = "http://steamcommunity.com/id/Winning117/games/?tab=all";
Document document = Jsoup.connect(url).get();
Element playTime = document.select("div#game_605250");
Elements val = playTime.select(".hours_played");
System.out.println(val.text());
}
}
I came across a really nice and simple xls and xlsx implementation API called Fillo. I've made a spread sheet with the following values as most people know the all caps sections are for category names to seac
USERID PASS
joe bigjoe
jim bigjim
john bigjohn
Now here's the code:
import Exception.FilloException;
import Fillo.*;
public class CallBack {
public static void main(String args[]) throws FilloException {
testFillo();
}
private static void testFillo() throws FilloException {
Fillo fillo=new Fillo();
Connection connection=fillo.getConnection("logindatabase.xls");
String strQuery="Select * from Sheet1 where USERID='*' and PASS='*'";
Recordset recordset=connection.executeQuery(strQuery);
/*
* I'm wanting the login check to be right here
*/
recordset.close();
connection.close();
}
}
The login function should go through the USERID column first and once it finds that it will check the corresponding PASS value. So if it found "jim" as the user it then check for "bigjim" as the password.
So the big question would be: How would I set something like this up?
Here's the Fillo Documentation.
All the best,
Groax
you can try this... It's not completely customized but it will help...
public static void selectData(String tcid,String fieldName) throws FilloException{
Fillo fillo=new Fillo();
Connection connection=fillo.getConnection("testdata//testcasedata.xlsx");
String strQuery="Select * from data where TCID='"+tcid+"'";
Recordset recordset=connection.executeQuery(strQuery);
while(recordset.next()){
ArrayList<String> dataColl=recordset.getFieldNames();
//System.out.println(dataColl);
Iterator<String> dataIterator=dataColl.iterator();
//System.out.println(dataColl.size());
while(dataIterator.hasNext()){
for (int i=0;i<=dataColl.size()-1;i++){
//System.out.println(i);
String data=dataIterator.next();
String dataVal=recordset.getField(data);
if (dataVal.equalsIgnoreCase(fieldName)){
//System.out.println("passed");
i=i+1;
//System.out.println(i);
String testData=dataColl.get(i);
System.out.println(recordset.getField(testData));
}
}
break;
}
}
recordset.close();
connection.close();
}
You will have to arrange your table like database as fillo works like database.
Put everything related to a test case in a row. as attached.
below is the code for reader and calling the login class.
package com.evs.vtiger.framework.util;
import java.util.ArrayList;
import java.util.Iterator;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import com.evs.vtiger.framework.pages.home.myhomepage.HomePage;
import Exception.FilloException;
import Fillo.Connection;
import Fillo.Fillo;
import Fillo.Recordset;
import com.evs.vtiger.framework.pages.login.login.LoginPage;
public class TestingFillo {
public static void main(String[] args) throws FilloException {
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://localhost:8080/NBOWeb");
LoginPage lpObj=PageFactory.initElements(driver, LoginPage.class);
lpObj.pg_ValidLogin("TC001");
}
public static String getTestValue(String TCID, String fieldName) throws FilloException{
String testString=xlTesting(TCID, fieldName);
return testString;
}
public static String xlTesting(String tcid,String fieldName) throws FilloException{
String testval=null;
Fillo fillo=new Fillo();
Connection connection=fillo.getConnection("TestData//TestData.xlsx");
String strQuery="Select * from data where TCID='"+tcid+"'";
Recordset recordset=connection.executeQuery(strQuery);
while(recordset.next()){
ArrayList<String> dataColl=recordset.getFieldNames();
//System.out.println(dataColl);
Iterator<String> dataIterator=dataColl.iterator();
//System.out.println(dataColl.size());
while(dataIterator.hasNext()){
for (int i=0;i<=dataColl.size()-1;i++){
//System.out.println(i);
String data=dataIterator.next();
String dataVal=recordset.getField(data);
if (dataVal.equalsIgnoreCase(fieldName)){
//System.out.println("passed");
i=i+1;
//System.out.println(i);
String testData=dataColl.get(i);
//System.out.println(recordset.getField(testData));
String testValue= recordset.getField(testData);
testval=testValue;
}
}
break;
}
}
recordset.close();
connection.close();
return testval;
}
public static void inputText(WebElement we, String fieldName, String TCID) throws FilloException{
String fval=getTestValue(TCID, fieldName);
we.sendKeys(fval);
}
}
Now here is the code of login
package com.evs.vtiger.framework.pages.login.login;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import Exception.FilloException;
import com.evs.vtiger.framework.pages.home.myhomepage.HomePage;
import com.evs.vtiger.framework.util.TestingFillo;
import com.evs.vtiger.framework.util.UI;
import com.evs.vtiger.framework.util.XLReader;
public class LoginPage {
#FindBy(name="username")
public WebElement UserName_ED;
#FindBy(xpath="//input[#type='password']")
public WebElement Password_ED;
#FindBy(xpath="//input[#value='login']")
public WebElement Login_BT;
public void pg_ValidLogin(String TCID) throws FilloException {
/*UI.fn_Input(UserName_ED, "UserName_ED");
UI.fn_Input(Password_ED, "Password_ED");
UI.fn_Click(Login_BT);*/
//UserName_ED.sendKeys("abc");
TestingFillo.inputText(UserName_ED, "UserName_ED", TCID);
TestingFillo.inputText(Password_ED, "Password_ED", TCID);
Login_BT.click();
// HomePage hpObj=PageFactory.initElements(UI.driver, HomePage.class);
// return hpObj;
}
public void pg_InValidLogin() {
UserName_ED.sendKeys("rahul");
Password_ED.sendKeys("admin");
Login_BT.click();
}
}
I hope it makes sense. Please ignore the commented code. sorry for that.
Thanks
Nitin
I downloaded the code below and used it for some tests and u=it ran yesterday but since today the code stopped working. My tests are failing now which was not happening before. It throws up an error saying org.openqa.selenium.ElementNotVisibleException: element is not currently visible so cannot interact with element.
package org.openqa.selenium.example;
//import org.openqa.selenium.browserlaunchers.locators.GoogleChromeLocator;
//import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
//import org.openqa.selenium.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
//import org.openqa.selenium.chrome.*;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.firefox.FirefoxDriver;
//import org.openqa.selenium.support.ui.Select;
//import org.openqa.selenium.net.UrlChecker;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class KongaUrlTest
{
private WebDriver driver;
private String baseUrl;
//private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception
{
driver = new FirefoxDriver();
baseUrl = "http://www.konga.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testFirefoxWebdriver() throws Exception
{
driver.get(baseUrl);
driver.findElement(By.cssSelector("a.vertnavlink > span")).click();
try
{
assertEquals("Phones & Tablets | Konga Nigeria", driver.getTitle());
System.out.println(driver.getTitle());
}
catch (Error e)
{
verificationErrors.append(e.toString());
}
}
#After
public void tearDown() throws Exception
{
System.out.println(driver.getCurrentUrl());
driver.quit();
}
}
There's a blocking dialog being displayed. It's probably displayed each time Selenium opens a new browser and navigates to that site. Close that dialog first:
driver.get(baseUrl);
try
{
driver.findElement(By.cssSelector(".fancybox-close")).click();
}
catch { }
driver.findElement(By.cssSelector("a.vertnavlink > span")).click();