In the below code on 33rd line getting below error message near wait.until
Multiple markers at this line
- The type com.google.common.base.Function cannot be resolved. It is indirectly referenced from required .class files
- The method until(Function) in the type FluentWait is not applicable for the
arguments (ExpectedCondition)
package MPA;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginhelperClass {
WebDriver driver;
#FindBy(xpath = "//input[#ng-model='login.username']")
private WebElement userName;
#FindBy(xpath = "//input[#type='password']")
private WebElement Password;
#FindBy(xpath = "//input[#type='submit' and #value='Sign In']")
private WebElement SignIn;
#FindBy(xpath = "//span[#class='icon-avatar-round']")
private WebElement Avatar;
public LoginhelperClass(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void logIn(String uName, String Pswd) throws InterruptedException {
WebDriverWait wait=new WebDriverWait(driver,7);
wait.until(ExpectedConditions.visibilityOf(userName));
userName.sendKeys(uName);
Password.sendKeys(Pswd);
SignIn.click();
try {
Thread.sleep(4000);
if (Avatar.isDisplayed()) {
System.out.println("Login Successfull: " + uName);
} else {
System.out.println("Login failure check the credentials: " + uName);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
package MPA;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginhelperClass {
WebDriver driver;
#FindBy(xpath = "//input[#ng-model='login.username']")
private WebElement userName;
#FindBy(xpath = "//input[#type='password']")
private WebElement Password;
#FindBy(xpath = "//input[#type='submit' and #value='Sign In']")
private WebElement SignIn;
#FindBy(xpath = "//span[#class='icon-avatar-round']")
private WebElement Avatar;
public LoginhelperClass(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void logIn(String uName, String Pswd) throws InterruptedException {
WebDriverWait wait=new WebDriverWait(driver,7);
wait.until(ExpectedConditions.visibilityOf(userName));
userName.sendKeys(uName);
Password.sendKeys(Pswd);
SignIn.click();
try {
Thread.sleep(4000);
if (Avatar.isDisplayed()) {
System.out.println("Login Successfull: " + uName);
} else {
System.out.println("Login failure check the credentials: " + uName);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
The error which you are seeing is as follows :
Multiple markers at this line - The type com.google.common.base.Function cannot be resolved. It is indirectly referenced from required .class files - The method until(Function) in the type FluentWait is not applicable for the arguments (ExpectedCondition)
Let us analyze what is happening in our code.
In the Page Object you have defined an WebElement as :
#FindBy(xpath = "//input[#ng-model='login.username']")
private WebElement userName;
Moving ahead you have tried to use the WebElement within the method :
public void logIn(String uName, String Pswd) throws InterruptedException {
WebDriverWait wait=new WebDriverWait(driver,7);
wait.until(ExpectedConditions.visibilityOf(userName));
//
}
So basically here we were trying to wait for the visibility of an Indirectly Referenced Angular WebElement userName which is dependent on the attribute ng-model. In such circumstances we can never be sure that when the WebElement will be referenced within a method userName will mandatory reference to a not NULL value. It may be NULL as well.
Now let us have a look at the Method Defination of visibilityOf, it is defined as :
visibilityOf(WebElement element)
An expectation for checking that an element, known to be present on the DOM of a page, is visible.
So clearly, visibilityOf method expects a Direct Reference of the WebElement. Hence in absence of a definite value (not NULL) of userName, WebDriverWait which is a variant of FluentWait shows the error.
Play with conditions with By/WebElement:
ExpectedConditions.presenceOfAllElementsLocatedBy(By)
ExpectedConditions.elementExists(By)
ExpectedConditions.elementIsVisible(By)
ExpectedConditions.elementToBeClickable(By/WebElement)
ExpectedConditions.visibilityOfAllElementsLocatedBy(By)
Related
I'm trying to search for something, after clicking the search button, the button going into an loading animation. If there is a result, it goes to the next page, if there is no result, a yellow box appears. How can I write this line new WebDriverWait(driver, 1).until? I'm thinking until the title change or the yellow box appears. But I'm not sure how can I code that.
This is what I got so far
new WebDriverWait(driver, 1).until(driver.getTitle().contains("Overview") || !driver.findElements(By
.xpath("/html/body/div[2]/div/div[3]/div/div[1]/div/div/div[2]/div[2]/div/div[1]/div/div/div/span"));
.isEmpty())
Use org.openqa.selenium.support.ui.ExpectedConditions
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public WebDriverWait waitSec(WebDriver driver, int sec) {
return new WebDriverWait(driver, sec);
}
public WebElement clickableByXpath(String xpath, int sec) {
WebElement element = waitSec(driver, sec).until(ExpectedConditions.elementToBeClickable(By.xpath(xpath)));
return element;
}
public WebElement clickableById(String id, int sec) {
WebElement element = waitSec(driver, sec).until(ExpectedConditions.elementToBeClickable(By.id(id)));
return element;
}
public WebElement visibleById(String id, int sec) {
WebElement element = waitSec(driver, sec).until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
return element;
}
public WebElement visibleByXpath(String xpath, int sec) {
WebElement element = waitSec(driver, sec).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
return element;
}
// custom ExpectedCondition
public ExpectedCondition<Boolean> elementNotVisible(String xpath) {
return ExpectedConditions.not(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
}
See https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html
I used these two classes to execute my program. In one class i have kept all my variables, in another class i have kept the code to be executed. But I am unable to execute the code. I am getting error message stating that Cannot instantiate class
package BalajiSanthanamAcademy.MavenJava;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class CommonVariableTest {
public static WebDriver driver=null;
public String key="webdriver.chrome.driver";
public String path="C:\\Program Files\\Java\\chromedriver_win32\\chromedriver.exe";
public String baseUrl = "https://www.expedia.co.in/";
public String expUrl = "https://www.expedia.co.in/";
public String Yatra = "https://www.yatra.com/";
public String expYatra = "https://www.yatra.com/";
//yatra search
WebElement departFrom =driver.findElement(By.xpath("//input[#id='BE_flight_origin_city']"));
//Flying From class variables
public String Depature = "CJB";
public String goingTo = "MAA";
//Flying To class variables
//Declaring departure and return date
public String departureDate = "07/22/2020";
public String returnDate = "10/15/2020";
}
and below class is the one which i used to execute
package BalajiSanthanamAcademy.MavenJava;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class YatraLoginTest extends CommonVariableTest {
WebDriver driver;
#BeforeClass
public void setup()
{
System.setProperty(key,path);
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
}
#Test (priority=1)
public void setBaseURL()
{
driver.get(Yatra);
System.out.println(driver.getCurrentUrl());
try{
Assert.assertEquals(expYatra, driver.getCurrentUrl());
System.out.println("Navigated to correct webpage");
}
catch(Throwable pageNavigationError)
{
System.out.println("Didn't navigate to correct webpage");
}
}
#Test (priority=2)
public void Login() throws InterruptedException
{
driver.findElement(By.cssSelector("body.wrapper-snipe.wrapper-toucan.tenantwrapper-dom.catwrapper-home:nth-child(2) div.theme-snipe:nth-child(2) div.yatra-header.headerGrp div.wrapper div.header-container.desktop-only div.header-right-menu.menu.ftL div.settings ul.justified-menu.desktop-navs.settings-content.responsivetabshow li.list-dropdown:nth-child(1) > a.dropdown-toggle")).click();
driver.findElement(By.cssSelector("#signInBtn")).click();
WebDriverWait w =new WebDriverWait(driver,10);
w.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[#id='login-input']")));
driver.findElement(By.xpath("//input[#id='login-input']")).click();
driver.findElement(By.xpath("//input[#id='login-input']")).sendKeys("balajimscit09#gmail.com");
Thread.sleep(2000L);
driver.findElement(By.cssSelector("#login-continue-btn")).click();
WebDriverWait x =new WebDriverWait(driver,10);
x.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#login-password")));
driver.findElement(By.cssSelector("#login-password")).click();
driver.findElement(By.cssSelector("#login-password")).sendKeys("Welcome-1");
driver.findElement(By.cssSelector("#login-submit-btn")).click();
}
#Test (priority=3)
public void HomepageValidation() throws InterruptedException
{
WebDriverWait Y =new WebDriverWait(driver,15);
Y.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[#class='dropdown-toggle loginUserName']")));
String Wel = driver.findElement(By.xpath("//a[#class='dropdown-toggle loginUserName']")).getText();
Assert.assertEquals(Wel,"Hi Balaji");
System.out.println(Wel+" = Login details Sucessfully validated");
}
#Test (priority=4)
public void yatraSearch() throws InterruptedException
{
//Round trip tab
driver.findElement(By.xpath("//a[#class='blur_class']")).click();
Thread.sleep(3000L);
//Depart from
departFrom.click();
Thread.sleep(3000L);
departFrom.sendKeys("CJB");
Thread.sleep(3000L);
departFrom.sendKeys(Keys.ENTER);
Thread.sleep(3000L);
departFrom.getAttribute("value");
//Going To
WebElement goinTo =driver.findElement(By.xpath("//input[#id='BE_flight_arrival_city']"));
Thread.sleep(3000L);
goinTo.sendKeys(goingTo);
Thread.sleep(3000L);
goinTo.sendKeys(Keys.ENTER);
driver.findElement(By.cssSelector("#BE_flight_origin_date")).click();
Thread.sleep(3000L);
WebElement element = driver.findElement(By.xpath("/html[1]/body[1]/div[2]/div[1]/section[1]/div[1]/div[1]/div[1]/section[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/ul[1]/li[2]/ul[1]/li[1]/section[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[1]/table[1]/tbody[1]/tr[2]/td[4]"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
Thread.sleep(3000L);
WebElement element1 = driver.findElement(By.xpath("//div[#class='month-box BE_flight_arrival_date']//div[1]//table[1]//tbody[1]//tr[2]//td[7]"));
Actions actions1 = new Actions(driver);
actions1.moveToElement(element1).click().build().perform();
driver.findElement(By.xpath("//span[#class='txt-ellipses flight_passengerBox travellerPaxBox']")).click();
for(int i=0;i<2;i++)
{
driver.findElement(By.xpath("//div[#class='iePasenger dflex']//div[1]//div[1]//div[1]//span[2]")).click();
driver.findElement(By.xpath("//div[#class='vertical_search_engine']//div[2]//div[1]//div[1]//span[2]")).click();
}
driver.findElement(By.cssSelector("#BE_flight_flsearch_btn")).click();
}
#Test (priority=5)
public void SearchValid() throws InterruptedException
{
System.out.println(driver.findElement(By.xpath("//input[#placeholder='Select Origin']")).getAttribute("value"));
System.out.println(driver.findElement(By.xpath("//input[#placeholder='Select Destination']")).getAttribute("value"));
System.out.println(driver.findElement(By.xpath("//input[#placeholder='Depart']")).getAttribute("value"));
System.out.println(driver.findElement(By.xpath("//input[#placeholder='Return']")).getAttribute("value"));
System.out.println(driver.findElement(By.xpath("//body/section[#id='flightSRP']/section/div/div/form[#id='modifySearch']/ul/li[5]/div[1]")).getAttribute("value"));
driver.findElement(By.xpath("//div[contains(#class,'result-set pr grid')]//div[2]//div[1]//div[1]//div[1]//div[4]//div[1]//div[1]//div[1]//label[1]//div[2]//i[1]")).getText();
driver.findElement(By.xpath("//section[#id='Flight-APP']//section//section//div//div//div//button")).click();
}
}
I am getting the below error message.
[RemoteTestNG] detected TestNG version 7.0.1
org.testng.TestNGException:
Cannot instantiate class BalajiSanthanamAcademy.MavenJava.YatraLoginTest
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:30)
at org.testng.internal.InstanceCreator.instantiateUsingDefaultConstructor(InstanceCreator.java:193)
at org.testng.internal.InstanceCreator.createInstanceUsingObjectFactory(InstanceCreator.java:113)
at org.testng.internal.InstanceCreator.createInstance(InstanceCreator.java:79)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:109)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:167)
at org.testng.TestClass.getInstances(TestClass.java:102)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:82)
at org.testng.TestClass.init(TestClass.java:74)
at org.testng.TestClass.<init>(TestClass.java:39)
at org.testng.TestRunner.initMethods(TestRunner.java:459)
at org.testng.TestRunner.init(TestRunner.java:338)
at org.testng.TestRunner.init(TestRunner.java:291)
at org.testng.TestRunner.<init>(TestRunner.java:222)
at org.testng.remote.support.RemoteTestNG6_12$1.newTestRunner(RemoteTestNG6_12.java:33)
at org.testng.remote.support.RemoteTestNG6_12$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_12.java:66)
at org.testng.ITestRunnerFactory.newTestRunner(ITestRunnerFactory.java:55)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:676)
at org.testng.SuiteRunner.init(SuiteRunner.java:178)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:112)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1275)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1251)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1100)
at org.testng.TestNG.runSuites(TestNG.java:1039)
at org.testng.TestNG.run(TestNG.java:1007)
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)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:23)
... 27 more
Caused by: java.lang.NullPointerException
at BalajiSanthanamAcademy.MavenJava.CommonVariableTest.<init>(CommonVariableTest.java:20)
at BalajiSanthanamAcademy.MavenJava.YatraLoginTest.<init>(YatraLoginTest.java:19)
... 33 more
Can you please help me how to resolve
The Root Cause is NullPointerException as shown in last few lines in your logs. The reason is this line -
public static WebDriver driver=null;
You need to create a new instance of WebDriver and assign it to the variable driver
Thank you for the co-ordination. I found the answer at last. The mistake is i have placed an web element in CommonVariableTest class, and tried to access the WebElement from YatraLoginTest class. Hence the error message wasthrown. when i removed the WebElement it is working fine.
Nullpointexception showing here that means url launched but driver instance not created to interact so to initially you have define driver driver as null
I want to use: Login_Page Login = PageFactory.initElements(driver, Login_Page.class); in a unique way in all steps.
When I use it for each step I have no problems, but on the contrary Java shows me the error: " Value driver is always 'null'".
I would also like to replace Thread.sleep (2000); for a better solution.
Here is my Code:
package stepdefs;
import Pages.Login_Page;
import cucumber.api.java.pt.Dado;
import cucumber.api.java.pt.Entao;
import cucumber.api.java.pt.Quando;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import java.util.concurrent.TimeUnit;
public class StepDefinitions {
WebDriver driver;
Login_Page Login = PageFactory.initElements(driver, Login_Page.class);
#Dado("^que que estou na pagina principal do Gmail\\.$")
public void que_que_estou_na_pagina_principal_do_Gmail () throws Exception
{
System.setProperty("webdriver.chrome.driver", "C:\\browsers\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("https://www.gmail.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Quando("^forneco as credenciais validas\\.$")
public void forneco_as_credenciais_validas () throws Exception {
// Login_Page Login = PageFactory.initElements(driver, Login_Page.class);
Login.setEmail("rbkamontana#gmail.com");
Login.ClickOnNextButton();
Thread.sleep(2000);
Login.setSenha("automation10");
Thread.sleep(3000);
Login.ClickOnEnterButton();
driver.manage().window().maximize();
Thread.sleep(3000);
}
#Entao("^posso ver que estou logado\\.$")
public void posso_ver_que_estou_logado () throws Exception {
driver.findElement(By.xpath("//*[#id=\"gb\"]/div[2]/div[3]/div[1]/div[2]/div/a/span")).click();
String stringAtual = driver.findElement(By.xpath("//*[#id=\"gb\"]/div[2]/div[4]/div[1]/div[2]/div[1]")).getText();
String StringEsperada = "Rebeka Montana";
Assert.assertTrue(stringAtual.contains(StringEsperada));
//driver.quit();
}
}
Instead of Thread.sleep you can use selenium WebDriverWait function by a Locator.
Ref:
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/WebDriverWait.html
void waitForElement(By Locator){
WebDriverWait myWait = new WebDriverWait(myDriver, 20);
myWait.until(ExpectedConditions.visibilityOfElementLocated(Locator));
}
Try initiating this inside of a constructor instead:
public StepDefinitions(){
driver = new ChromeDriver();
Login = PageFactory.initElements(driver, Login_Page.class);
}
An instance method is initializing the driver field at runtime, which explains why things work inside the step definition method. The solution is deceptively simple: create a getter method for the page model:
public class StepDefinitions {
WebDriver driver;
Login_Page login;
private Login_Page getLoginPage() {
if (login == null) {
login = PageFactory.initElements(driver, Login_Page.class);
}
return login;
}
#Quando("^forneco as credenciais validas\\.$")
public void forneco_as_credenciais_validas () throws Exception {
Login_Page login = getLoginPage();
login.setEmail("rbkamontana#gmail.com");
login.ClickOnNextButton();
Thread.sleep(2000);
login.setSenha("automation10");
Thread.sleep(3000);
login.ClickOnEnterButton();
driver.manage().window().maximize();
Thread.sleep(3000);
}
I had tried to create method and call it from another file to the main class but It won't work the error message said "java.lang.NullPointerException"
Main.class
Keywords kw = new Keywords();
#When("^gmailDD$")
public void gmailDD() throws Throwable{
WebDriverWait wait5s = new WebDriverWait(driver, 5);
String regis = "/html/body/div[2]/div[1]/div[5]/ul[1]/li[3]/a";
String dd = "/html/body/div[1]/div/footer/div/div/div[1]";
String empty = "/html/body/div[1]/div/footer";
kw.clickbyxpath(regis);
String handle= driver.getWindowHandle();
System.out.println(handle);
// Store and Print the name of all the windows open
Set handles = driver.getWindowHandles();
System.out.println("Log window id: "+handles);
driver.switchTo().window("6442450949");
kw.clickbyxpath(empty);
kw.clickbyxpath(dd);
}`
Method.class
WebDriver saddriver;
public void clickbyxpath (String xpathvalue) throws InterruptedException, IOException
{
WebDriverWait sad = new WebDriverWait(saddriver, 10);
//To wait for element visible
System.out.println(xpathvalue);
String x = xpathvalue;
sad.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(x)));
wowdriver.findElement(By.xpath(x)).click();
}
I had tried to do the same coding in the same file, It has no problem but when I move Method.class to the new file, error message said "java.lang.NullPointerException" but I can get "xpathvalue" value.
This Error occur because of it will not able to find your driver instance.
refer below code snippet. this is not cucumber example but you can get idea by this.
Method.class
package testing.framework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Method {
public WebDriver driver;
WebElement _clickForSearch;
public Method(WebDriver driver) {
this.driver = driver;
}
public Method clickByXpath(String xpathValues) {
WebDriverWait wait = new WebDriverWait(driver, 10);
_clickForSearch = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpathValues)));
_clickForSearch.click();
return this;
}
}
Testing.class
package testing.framework;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Testing {
public static WebDriver driver;
public static void main(String[] args) {
getWebDriver();
String xpathValues= "//div[#class='FPdoLc VlcLAe']//input[#name='btnK']";
Method m1 = new Method(driver);
m1.clickByXpath(xpathValues);
}
public static void getWebDriver() {
System.setProperty("webdriver.chrome.driver", "Your chrome driver path");
driver = new ChromeDriver();
driver.get("https://www.google.com");
}
}
You need to pass your driver instance to another.
So I would suggest you take the webdriver wait out of your method and instantiate it when instantiating your webdriver. I would then create methods like so:
Driver class
private final String USER_DIRECTORY = System.getProperty("user.dir");
private final int GLOBAL_TIMEOUT = 30;
private WebDriver webDriver;
private WebDriverWait webDriverWait;
public Driver(String browserName) {
this.browserName = browserName;
System.out.println(browserName);
switch (this.browserName.toUpperCase()) {
case "CHROME":
initializeChromeDriver();
break;
}
}
private void initializeChromeDriver() {
System.setProperty("webdriver.chrome.driver", USER_DIRECTORY.concat("\\drivers\\chromedriver.exe"));
webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
webDriverWait = new WebDriverWait(webDriver, GLOBAL_TIMEOUT);
}
Click method
public void buttonClickByXpath(String xpath) {
try {
WaitForPreseneOfElement(xpath);
webDriver.findElement(By.xpath(xpath)).click();
} catch (Exception e) {
takeScreenshot();
AllureLog("Failed to click on the button object. Please check your xpath. | xpath used = " + xpath + "");
Assert.fail();
}
}
Test Class
Import your driver class
import Base.Driver;
Then you would need declair your driver class like so:
Driver driver;
Now you will have access to your method using
driver.buttonClickByXpath(//YourXpathHere)
The problem is "Method m1 = new Method(driver);" keyword,
I had coded this line outside the main method.
thank you very much, Sir
I've written a code using Selenium WD and JUnit that should check if proper page is loaded and the table of this page is not null
Besides assertion, to make sure that proper page is loaded (checking if URL contains specified text), I've put "if-else" statement in "waitUntilPageLoaded" method.
import junit.framework.TestCase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.junit.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class GuruSearch
{
#Test
static void checkDemoLogin()
{
System.setProperty("webdriver.gecko.driver", "C:\\Users\\pansa\\Documents\\Webdrivers\\geckodriver.exe");
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://demo.guru99.com/");
TestCase.assertFalse(driver.getPageSource().contains("404"));
driver.manage().window().maximize();
//odczekaj(5000);
WebElement browser = driver.findElement(By.name("emailid"));
browser.sendKeys("Test#test.com");
browser.submit();
waitUntilPageLoaded(driver,"access.php", 10);
TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"));
WebElement table = driver.findElement(By.tagName("tbody"));
TestCase.assertNotNull(table);
driver.close();
}
static private void odczekaj(int czas)
{
try {
Thread.sleep(czas);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Przerwanie");
}
}
private static void waitUntilPageLoaded(FirefoxDriver d, String zawiera, int timeout)
{
WebDriverWait wait = new WebDriverWait(d, timeout);
wait.until(ExpectedConditions.urlContains(zawiera));
if (d.getCurrentUrl().contains(zawiera))
{
System.out.println("OK");
}
else
{
System.out.println("NOK");
}
}
}
The "if-else" statement in "waitUntilPageLoaded" method returns "OK", but TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"))
throws AssertionError, although the text appears in the page.
Why there is AssertionError thrown?
As you are using the JUnit annotations, the annotated method shouldn't be static. I have modified your code a bit, try the below:
import org.junit.Test;
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.WebDriverWait;
import junit.framework.TestCase;
public class GuruSearch
{
#Test
public void checkDemoLogin()
{
System.setProperty("webdriver.chrome.driver", "C:\\NotBackedUp\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demo.guru99.com/");
TestCase.assertFalse(driver.getPageSource().contains("404"));
driver.manage().window().maximize();
//odczekaj(5000);
WebElement browser = driver.findElement(By.name("emailid"));
browser.sendKeys("Test#test.com");
browser.submit();
waitUntilPageLoaded(driver,"access.php", 30);
TestCase.assertTrue(driver.getPageSource().contains("Access details to demo site"));
WebElement table = driver.findElement(By.tagName("tbody"));
TestCase.assertNotNull(table);
driver.close();
}
static private void odczekaj(int czas)
{
try {
Thread.sleep(czas);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Przerwanie");
}
}
private static void waitUntilPageLoaded(WebDriver d, String zawiera, int timeout)
{
WebDriverWait wait = new WebDriverWait(d, timeout);
wait.until(ExpectedConditions.urlContains(zawiera));
if (d.getCurrentUrl().contains(zawiera))
{
System.out.println("OK");
}
else
{
System.out.println("NOK");
}
}
}
The above code is printing 'OK' and Assert condition also passing. And I think, it doesn't matter if we give upper/lower case in the contains. It will match both the cases.
I don't have Firefox in my system so I have checked with Chrome, you change the browser and try... I hope it helps...