Selenium test runs won't save cookies? - java

So I'm experimenting with Selenium automation, and I'm trying to write a testcase that logs in, goes to a specific page, inputs data, then presses submit. The issue is that when it runs, it types out the credentials, presses "Submit" the site returns:
This site uses HTTP cookies to verify authorization information.
Please enable HTTP cookies to continue.
But then when I added this line [denoted by //1]:
driver.findElement(By.cssSelector("p > input[type=\"submit\"]")).click();
It allowed the login to go through until it gets to the send message page [denoted by //2], it asks for credentials again (as if no login was ever made). So is firefox not accepting cookies at all? How do I fix this?
Source:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class LaPwn {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String UserID = "";
private String UserPW = "";
private String UserPIN = "";
public static void main(String[] args) throws Exception {
UserInfo User = new UserInfo();
User.setUserInfo();
System.out.println(User.getUserID());
System.out.println(User.getUserPW());
System.out.println(User.getUserPIN());
JUnitCore.main("LaPwn");
}
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://my_url.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testLaPwn() throws Exception {
driver.get(baseUrl + "/Login");
//1
driver.findElement(By.cssSelector("p > input[type=\"submit\"]")).click();
//1
driver.findElement(By.id("UserID")).clear();
driver.findElement(By.id("UserID")).sendKeys("User.getUserID()");
driver.findElement(By.name("PIN")).clear();
driver.findElement(By.name("PIN")).sendKeys("User.getUserPW()");
driver.findElement(By.cssSelector("p > input[type=\"submit\"]")).click();
driver.findElement(By.id("apin_id")).sendKeys("User.getUserPIN()");
driver.findElement(By.cssSelector("div.pagebodydiv > form > input[type=\"submit\"]")).click();
//2
driver.get(baseUrl + "/messagecenter");
//2
try {
assertEquals("Send message:", driver.getTitle());
} catch (Error e) {
verificationErrors.append(e.toString());
}
driver.findElement(By.id("user")).clear();
driver.findElement(By.id("user")).sendKeys("test123");
driver.findElement(By.id("messg")).clear();
driver.findElement(By.id("messg")).sendKeys("Hello test123!");
driver.findElement(By.xpath("(//input[#name='SEND_BTN'])[2]")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}

Based on your problem statement, the problem you are facing is that selenium is opening a fresh firefox profile where cookies are not enabled.
driver = new FirefoxDriver();
This is where you have to fix in such a way that it opens up a profile where cookies are enabled.
One way is to create your own profile in firefox and open that profile instead of directly opening by FirefoxDriver();
ProfilesIni profileObj = new ProfilesIni();
FirefoxProfile yourFFProfile = profileObj.getProfile("your profile");
driver = new FirefoxDriver(yourFFProfile);
This way you can do what ever setting you need to in that profile and run your tests under that settings. If enabling cookies is the need, do that in firefox options.
Following is another way to open a specific profile as per seleniumhq.org
File profileDir = new File("path/to/top/level/of/profile");
FirefoxProfile profile = new FirefoxProfile(profileDir);
profile.addAdditionalPreferences(extraPrefs);
WebDriver driver = new FirefoxDriver(profile);
Check the source for more info on this topic.
Source: http://docs.seleniumhq.org/docs/03_webdriver.jsp#modifying-the-firefox-profile

I actually realized I defined the base URL as
baseUrl = "https://my_url.com/";
and it was concatenating it like:
driver.get(baseUrl + "/Login");
for "https://my_url.com//Login". Thanks for your replay though!

Related

org.openqa.selenium.NoSuchSessionException: Session ID is null error

When i am trying to run my selenium tests the first test seem to work correctly but then i am recieving this error for the subsequent tests, Im after switching my tests over to an electron app so not sure if this is after causing a issue :
org.openqa.selenium.NoSuchSessionException: Session ID is null. Using WebDriver after calling quit()?
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
My set up page is:
public class SetUp extends TestRail {
private static ChromeDriver browser;
public static String urlHost;
public static String testEnv;
public static PageConfig pageConfig;
#Before
public void initialBrowser() {
if(browser == null) {
String projectLocation = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver", projectLocation + "/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
options.addArguments("start-maximized");
options.addArguments("--disable-gpu");
options.addArguments("disable-infobars");
System.setProperty("webdriver.chrome.silentOutput", "true");
options.setBinary("C:/Users/ElectronApp.exe");
browser = new ChromeDriver(options);
//--------------------
pageConfig = new PageConfig(browser);
}
}
//method: To get the url configs for the environment used to run the test
//#parameter: dev or test. demo doesn't not have a separate front end url
public void beforeTest(#NotNull final String env) throws Exception {
testEnv = env;
System.out.println("TEST ENVIRONMENT: " + testEnv);
switch (env){
case "qa-84" :
urlHost = "http://ukdc1-docker-mx:84/qa/#/login";
break;
case "qa-85":
urlHost = "http://ukdc1-docker-mx:85/qa/#/login";
break;
default:
throw new Exception("Incorrect environment passed");
}
}
//method to close the browser after every cucumber scenario
#After
public void closeBrowser(Scenario scenario) throws IOException, APIException {
if(scenario.isFailed()){
try{
TakesScreenshot screenshot = (TakesScreenshot)browser;
File source = screenshot.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("logs/screenshots/" + scenario.getName() + ".png"));
System.out.println("Screenshot taken");
} catch (Exception e){
System.out.println("Exception while taking screenshot " + e.getMessage());
}
}
browser.quit();
writeResultToTestRail(scenario);
}
public void writeResultToTestRail(Scenario scenario) throws IOException, APIException {
String tesCaseID = new String();
for(String s: scenario.getSourceTagNames()){
if(s.contains("TestRail")){
int size = s.length();
int startOfID = s.indexOf('"');
tesCaseID = s.substring(startOfID + 1,size - 2);
}
Map data = new HashMap();
if(scenario.isFailed()){
data.put("status_id", 5);
data.put("comment", "Test Env: " + urlHost + "\n\n" + logError(scenario));
}else {
data.put("status_id", 1);
}
postTestCaseStatus("add_result_for_case/","3914", tesCaseID, data);
//3914
}
}
protected void getTestCaseDetailsInConsole(String testCaseId) throws IOException, APIException {
System.out.println(getTestCaseDetails(testCaseId));
}
private static String logError(Scenario scenario) {
try {
Class klass = ClassUtils.getClass("cucumber.runtime.java.JavaHookDefinition$ScenarioAdaptor" );
Field fieldScenario = FieldUtils.getField(klass, "scenario", true);
if (fieldScenario != null) {
fieldScenario.setAccessible(true);
Object objectScenario = fieldScenario.get(scenario);
Field fieldStepResults = objectScenario.getClass().getDeclaredField("stepResults" );
fieldStepResults.setAccessible(true);
ArrayList<Result> results = (ArrayList<Result>) fieldStepResults.get(objectScenario);
for (Result result : results) {
if (result.getError() != null) {
System.out.println(result.getError() + "\n\n" + result.getErrorMessage());
if(result.getErrorMessage().length() > 3100) {
return result.getErrorMessage().substring(0, 3100);
} else {
return result.getErrorMessage();
}
}
}
}
return "Fetching error logs from the scenario ran into some issue, please check jenkins logs";
} catch (IllegalAccessException | NoSuchFieldException | ClassNotFoundException e) {
return e.getMessage();
}
}
}
And My Page config:
public class PageConfig {
public ChromeDriver browser;
public PageConfig(ChromeDriver browser){
this.browser = browser;
}
//method: Get instance method can be called on any class, it helps to avoid to add a line every time a new PO is added to the project.
//#parameter: ClassName.class
//#example: PageConfig.GetInstance(LoginPage.class).onLoginPage(); where onLoginPage is an method of
LoginPage.
public <TPage extends BasePage> TPage GetInstance (Class<TPage> pageClass){
try {
return initElements(browser, pageClass);
}catch(Exception e){
e.printStackTrace();
throw e;
}
}
}
the error shows that your driver close before the execution of the code, so the code of #After is directly executed so what I think is that you forget to use #Test in your set up page because there is #Before and #After but I don't see #Test.

Cucumber Selenium - Java - PageFactory : Step Definition: java.lang.NullPointerException

Hi community: I'm facing the next issue: I'm working with Cucumber, Selenium WebDriver using Page Factory. The error getting here is from the Step Definition side:
java.lang.NullPointerException
at pages.page_First.startNavigation(page_First.java:33)
at stepdefs.stepdefs_First.iGoToGoogle(stepdefs_First.java:20)
at ✽.I go to Google (file:src/test/resources/features/first.feature:10)
This is the part of the code (StepDefinition) where issue occurs:
#Given("I go to Google")
public void iGoToGoogle() {
page_first.startNavigation();
}
From the Page side, this is the code:
public class page_First extends BasePage {
public page_First() {
PageFactory.initElements(driver, this);
}
///////////////////////WEB ELEMENTS///////////////////////
#FindBy(name = "q")
private WebElement searchText;
#FindBy(name="btnK")
private WebElement searchButton;
//////////////////////BASE METHODS//////////////////////
public void startNavigation() {
driver.get(PropertyManager.getInstance().getURL());
}
public void search(String search) {
setTextAs(searchText, search);
}
public void enterButton (){
clickElement(searchButton);
}
}
The feature file:
Scenario Outline: Search google.com to verify google search is working
Given I go to Google
When I query for "<search>" cucumber spring selenium
And click search
Then google page title should become the first page
Examples:
| search |
| Cucumber Selenium |
This is my Browser class:
public class Browser {
// Take the instance of WebDriver
public static WebDriver driver;
public WebDriver initializeBrowser() throws IOException {
//Properties taken from config.properties
String browser = PropertyManager.getInstance().getBrowser();
if(browser.equals("chrome")) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
} else if(browser.equals("firefox")) {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
} else if(browser.equals("ie")) {
WebDriverManager.iedriver().setup();
driver = new InternetExplorerDriver();
} else if(browser.equals("edge")) {
WebDriverManager.edgedriver().setup();
driver = new EdgeDriver();
} else if(browser.equals("opera")) {
WebDriverManager.operadriver().setup();
driver = new OperaDriver();
} else {
System.setProperty("webdriver.safari.driver","/usr/bin/safaridriver");
driver = new SafariDriver();
}
System.out.println("-----> Proceed to initialize driver <-----");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
}
and here is my configuration property reader class:
public class PropertyManager {
private static PropertyManager instance;
private static final Object lock = new Object();
private static String propertyFilePath = System.getProperty("user.dir") + "//src//main//resources//data//config.properties";
///////////////////////////// DATA IN PROPERTIES //////////////////////////
private static String url;
private static String browser;
//Create a Singleton instance. We need only one instance of Property Manager.
public static PropertyManager getInstance () {
if (instance == null) {
synchronized (lock) {
instance = new PropertyManager();
instance.loadData();
}
}
return instance;
}
//Get all configuration data and assign to related fields.
private void loadData() {
//Declare a properties object
Properties prop = new Properties();
//Read config.properties file
try {
prop.load(new FileInputStream(propertyFilePath));
} catch (IOException e) {
System.out.println("Configuration properties file cannot be found");
}
//Get properties from config.properties
url = prop.getProperty("url");
browser = prop.getProperty("browser");
}
public String getURL () {
return url;
}
public String getBrowser () {
return browser;
}
}
I was forgetting this, my Step Definition class:
public class stepdefs_First {
private page_First page_first = PageFactory.initElements(Browser.driver, page_First.class);
#Given("I go to Google")
public void iGoToGoogle() {
page_first.startNavigation();
}
#When("I query for {string} cucumber spring selenium")
public void iQueryForCucumberSpringSelenium(String search) throws Exception {
page_first.search(search);
}
#And("click search")
public void clickSearch() {
page_first.enterButton();
}
#Then("google page title should become the first page")
public void googlePageTitleShouldBecomeTheFirstPage() {
System.out.println("All OK");
}
}
By the way, this is my config.properties
browser = firefox
url = https://www.google.cl
Please I need your help.
Initialize the Page Object class
page_First page_first=new page_First();

Stale element reference: element is not attached to the page document for Java-Selenium

What I am trying to do is after logging in, driver will click on Property dropdown, select an option and click on submit and repeat the process until the loop is complete.
Below is my code:
package com.genericlibrary;
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.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.util.Highlighter;
public class MobopsSearchJobsFromDropDown {
WebDriver driver;
Highlighter color;
public void getSetup() {
String path = System.getProperty("user.dir");
String driverPath = path + "\\Driver\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", driverPath);
driver = new ChromeDriver();
driver.navigate().to("http://mobops-test.jcdecauxna.com/");
driver.manage().window().maximize();
}
public void logIntoMobops() {
WebElement userName = driver.findElement(By.xpath("//*[contains(#id,'username')]"));
WebElement passWord = driver.findElement(By.xpath("//*[contains(#id,'password')]"));
WebElement loginButton = driver.findElement(By.xpath("//*[contains(text(),'Login')]"));
userName.sendKeys("test2");
passWord.sendKeys("1234");
loginButton.click();
}
public void selectEachPropertyAndSeachJob() {
WebElement dateRange = driver.findElement(By.xpath("//*[contains(#name,'date_range')]"));
WebElement last7days = driver.findElement(By.xpath("(//*[contains(text(),'Last 7 Days')])[2]"));
WebElement searchJobs = driver.findElement(By.xpath("//*[contains(#name,'layout')]"));
WebElement propertyDropdown = driver.findElement(By.xpath("//*[contains(#id,'property_id')]"));
Select dropdown = new Select(propertyDropdown);
List<WebElement> optionsInPropertyDropdown = dropdown.getOptions();
for (int i = 0; i < optionsInPropertyDropdown.size(); i++) {
if (propertyDropdown.isDisplayed() && propertyDropdown.isEnabled()) {
try {
propertyDropdown.click();
dropdown.selectByVisibleText(optionsInPropertyDropdown.get(i).getText());
dateRange.click();
last7days.click();
searchJobs.click();
System.out.println("Option Search is " + optionsInPropertyDropdown.get(i).getText());
} catch (org.openqa.selenium.StaleElementReferenceException ex) {
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOf(propertyDropdown));
}
}
}
}
public static void main(String[] args) {
MobopsSearchJobsFromDropDown obj = new MobopsSearchJobsFromDropDown();
obj.getSetup();
obj.logIntoMobops();
obj.selectEachPropertyAndSeachJob();
}
}
Right now it driver just select the first option and clicks on submit. Right after the page loads after the search completes I get the following error:
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
I have tried to implement the following code in my code, but since I am a novice, I have no idea how to implement the following to fix the issue:
new WebDriverWait(driver, timeout)
.ignoring(StaleElementReferenceException.class)
.until((WebDriver d) -> {
d.findElement(By.xpath("//*[contains(#id,'property_id')]")).click();
return true;
});
Any help to overcome this issue is greatly appreciated. Thanks.
Someone helped me with the problem. Below is the solution:
public class MobopsSearchJobsFromDropDown {
WebDriver driver;
HighLighter color;
public void getSetup() throws Throwable {
String path = System.getProperty("user.dir");
String driverPath = path + "\\driver\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", driverPath);
driver = new ChromeDriver();
driver.navigate().to("http://mobops-test.jcdecauxna.com/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
public void logIntoMobops() throws Throwable {
WebElement userName = driver.findElement(By.xpath("//*[contains(#id,'username')]"));
WebElement passWord = driver.findElement(By.xpath("//*[contains(#id,'password')]"));
WebElement loginButton = driver.findElement(By.xpath("//*[contains(text(),'Login')]"));
userName.sendKeys("test2");
passWord.sendKeys("1234");
loginButton.click();
}
public void selectEachPropertyAndSeachJob() throws Throwable {
WebDriverWait wait = new WebDriverWait(driver, 30);
List<WebElement> dropdownoptions = driver.findElements(By.xpath("//select[#id = 'property_id']//option"));
for(int i =0; i<dropdownoptions.size(); i++) {
String propertyDropdown = "//*[contains(#id,'property_id')]";
String dateRange = "//*[contains(#name,'date_range')]";
String last7days = "(//*[contains(text(),'Last 7 Days')])[2]";
String searchJobs = "//*[contains(#name,'layout')]";
Select dropdown = new Select(waitMethod(propertyDropdown));
WebElement option = dropdown.getOptions().get(i);
wait.until(ExpectedConditions.not(ExpectedConditions.stalenessOf(option)));
dropdown.selectByVisibleText(option.getText());
System.out.println(option.getText());
waitMethod(dateRange).click();
waitMethod(last7days).click();
waitMethod(searchJobs).click();
driver.navigate().refresh();
}
}
public WebElement waitMethod(String waiting) {
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement waitForRefresh =wait.until(ExpectedConditions.refreshed(ExpectedConditions.presenceOfElementLocated(By.xpath(waiting))));
return waitForRefresh;
}
public static void main(String[] args) throws Throwable {
MobopsSearchJobsFromDropDown obj = new MobopsSearchJobsFromDropDown();
obj.getSetup();
obj.logIntoMobops();
obj.selectEachPropertyAndSeachJob();
}
}
After you execute searchJobs.click(); your page reloads, so all references to previously found elements are lost.
You need to get all your WebElements, Select dropdown, and list of options again after searchJobs.click(); before using them second time.
So do not save webelements.
Something like this should work:
public void selectEachPropertyAndSeachJob() {
Select dropdown = new Select(driver.findElement(By.xpath("//*[contains(#id,'property_id')]")));
List<WebElement> optionsInPropertyDropdown = dropdown.getOptions();
for (int i = 0; i < optionsInPropertyDropdown.size(); i++) {
if (driver.findElement(By.xpath("//*[contains(#id,'property_id')]")).isDisplayed()) {
//propertyDropdown.click(); no need to click
dropdown.selectByVisibleText(optionsInPropertyDropdown.get(i).getText());
driver.findElement(By.xpath("//*[contains(#name,'date_range')]")).click();
driver.findElement(By.xpath("(//*[contains(text(),'Last 7 Days')])[2]")).click();
driver.findElement(By.xpath("//*[contains(#name,'layout')]")).click();
// Need to find it again
dropdown = new Select(driver.findElement(By.xpath("//*[contains(#id,'property_id')]")));
optionsInPropertyDropdown = dropdown.getOptions();
System.out.println("Option Search is " + optionsInPropertyDropdown.get(i).getText());
}
}
}
Instead of using driver.findElement every time, you can save your locators as By elements and create custom find method.

Selenium GRID Test execution

I am trying hard to run my Selenium Test not local but in a grid.
I thought I am doing good but I don´t get it to run.
HUB and NODE are Up and running(started with CMD) and I am using the right IP adresses.
Please let me know what I am doing wrong! Do you think it maybe could be a problem with a proxy?
Greetings Arno (student from Germany)
// Import all the stuff I need
public class MpreisScreenshot_ID {
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
String requiredBrowser = "firefox";
}
//the "if" underneath is just for a selection (to make it better to read
// I deleted the others)
if (requiredBrowser == "firefox")
{
DesiredCapabilities capabilityFirefox = DesiredCapabilities.firefox();
capabilityFirefox.setBrowserName("firefox");
capabilityFirefox.setVersion("54");
WebDriver driver= new RemoteWebDriver(new
URL("http://***.***.***.**:4445/grid/register"),capabilityFirefox);
}
baseUrl = "http://*****/****";
// driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
WebDriver driver;
#Test
public void captureScreenshot() throws Exception
{
//Start of Selenium test
// Maximize the browser
driver.manage().window().maximize();
// deleted all the steps
#AfterMethod
public void tearDown(ITestResult result)
{
// Test failing or Passing?
if(ITestResult.FAILURE==result.getStatus())
{
try
{
// Create reference of TakesScreenshot
TakesScreenshot ts=(TakesScreenshot)driver;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String uhrzeit= sdf.format(timestamp);
// Call method to capture screenshot
File source=ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("D:\\DATA\\Selenium\\TestNG-
Screenshots\\"+result.getName()+uhrzeit+".png"));
System.out.println("Screenshot taken");
}
catch (Exception e)
{
System.out.println("Exception while taking screenshot "+e.getMessage());
}
}
// close application
driver.quit();
}
}
Check your url, usually the default port for the Selenium Hub is 4444, also try the following:
http://youripaddress:4444/wd/hub/

Selenium : Unable to identify object using data provider

Beginner in this space, appreciate your help on the problem!
I'm trying to script a path
Login
create new user
log out
Login method works fine
Create user is dependent on Login method to be completed, using data providers and post login to create new user
Issue is after logging in the elements/objects in create user class are not identified. I have tried it using different element finders and browsers. Appreciate if you help around
Project Structure is
Project
Package1
Logindataprovider.class
newaccountDataProvider.class
Package2
LoginpageObjects.class
NewAccountPageObjects.class
Package3
LoginTestscripts.class
NewAccountTestScript.class
LoginTestscripts- Class
LoginPageObjects LgnObj = new LoginPageObjects();
#Test(groups = { "Logingroup1" }, dataProvider = "LoginCred", dataProviderClass = LoginDataProviders.class)
public void mytest(String DDUname, String DDpwd,String ExpLoginPage, int Browsertype) {
LgnObj.setBrowser(Browsertype);
Logger log = Logger.getLogger(LoginDataProviders.class);
log.info("Login To application method");
LgnObj.init();
// Login page assertion actual values
String LoginPageAssertactual = LgnObj.LoginPageAssertionActual();
//Login page assertion
Assert.assertEquals(LoginPageAssertactual, ExpLoginPage);
//login to application
LogginCommonProcess(DDUname, DDpwd, LgnObj);
}
public void LogginCommonProcess(String DDUname, String DDpwd,
LoginPageObjects LgnObj) {
LgnObj.enterUserName(DDUname);
LgnObj.enterPassword(DDpwd);
LgnObj.Loginbtn();
LgnObj.enterPIN();
LgnObj.CompanyName();
}
Logindataprovider- Class
public class LoginPageObjects {
WebDriver driver;
public void setBrowser(int type) {
if (type == 1) {
driver = new FirefoxDriver();
} else if (type == 2) {
String path = ClassLoader.getSystemResource("chromedriver.exe")
.getPath();
System.setProperty("webdriver.chrome.driver", path);
driver = new ChromeDriver();
} else if (type == 3) {
String path = ClassLoader.getSystemResource("IEDriverServer.exe")
.getPath();
System.setProperty("webdriver.ie.driver", path);
driver = new InternetExplorerDriver();
}
}
public void init() {
driver.manage().window().maximize();
driver.navigate().to("https://test2.qatest.com/Login.aspx");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
public String LoginPageAssertionActual() {
String LoginPageAssertionact = driver.findElement(By.tagName("h1"))
.getText();
return LoginPageAssertionact;
}
public void enterUserName(String DDUname) {
driver.findElement(By.id("ctl00_MainContent_usernameField")).sendKeys(
DDUname);
}
public void enterPassword(String DDpwd) {
driver.findElement(By.id("ctl00_MainContent_passwordField")).sendKeys(
DDpwd);
}
New User- page object
public class NewUser {
WebDriver driver;
public void setup() {
System.out.println("Start here");
System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
driver.manage().window().maximize();
driver.navigate().to("https://test2.directorsdesk.com/Login.aspx");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
public void setBrowser(int type) {
if (type == 1) {
driver = new FirefoxDriver();
} else if (type == 2) {
String path = ClassLoader.getSystemResource("chromedriver.exe")
.getPath();
System.setProperty("webdriver.chrome.driver", path);
driver = new ChromeDriver();
} else if (type == 3) {
String path = ClassLoader.getSystemResource("IEDriverServer.exe")
.getPath();
System.setProperty("webdriver.ie.driver", path);
driver = new InternetExplorerDriver();
} else if (type == 4) {
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setVersion("38");
cap.setPlatform(Platform.WINDOWS);
try {
driver = new RemoteWebDriver(new URL(
"http://127.0.0.1:4444/wd/hub"), cap);
} catch (MalformedURLException e) {
// log erro unable to access remote system, running in local
// firefox
driver = new FirefoxDriver();
}
}
}
**public void ManageSystem() {
driver.findElement(By.partialLinkText("Manage System")).click();
driver.findElement(By.linkText("Manage System")).click();
}**
public class NewAccount {
#Test(dataProvider = "UserDetails", dataProviderClass = LoginDataProviders.class, dependsOnGroups = "Logingroup1")
public void CreateNewAccount(String Emailid, String Firstname,
String Lastname, String PrimaryEmailid, int browserType) {
NewUser NewUserObj = new NewUser();
NewUserObj.setBrowser(browserType);
**NewUserObj.ManageSystem();** // Fails here
NewUserObj.UserAccounts();
NewUserObj.NewUserAccount();
NewUserObj.Emailid(Emailid);
NewUserObj.UserFirstname(Firstname);
NewUserObj.UserLastname(Lastname);
NewUserObj.PrimaryEmai(PrimaryEmailid);
NewUserObj.SaveAccountSettings();
LoginPageObjects LgnPgObj = new LoginPageObjects();
LgnPgObj.Logout();
LgnPgObj.closeBrowser();
}
Have you tried this:
public void entityFieldIsEntered(String field, String value) {
WebElement valueElem = new SharedDriver().findElement(By.xpath("(.//*[text()='" + field
+ ":'])[2]/parent::*/span/input"));
valueElem.sendKeys(new CharSequence[] { value });
}
assuming you are using input wrapper in your html. This code search for text label on the screen, then goes to its parent and navigate to input field.
If you are going to use multiple page objects in one test, you will need to share the same driver between those page objects.
Try creating a separate setupDriver class and have each page object take a driver parameter to be constructed.
At the beginning of each test setup the driver, then pass in the driver as you create each object.

Categories

Resources