I`m trying to perform a long press action on AndroidElement in Appium. What I found is that i need to perform a TouchAction on this element, but... it only takes as argument WebDriver, no AndroidDriver that I`m using. For this reason it will not work.
TouchAction action = new TouchAction(AndroidDriver);
action.longPress(element, 10000);
I was looking for some answer for some time. LongPress (or something similar) is used in last test that I`m writting right now.
Try this.
TouchAction action = new TouchAction();
action.longPress(webElement).release().perform();
Workaround could be usage of io.appium.java_client.MultiTouchAction.
MultiTouchAction multiTouch = new MultiTouchAction(AndroidDriver);
multiTouch.add(createTap(element, duration));
multiTouch.perform();
Below code will perform single tap and long press for particular period of time in android app
Make use of it
package com.prac.com;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebElement;
import io.appium.java_client.TouchAction;
import static io.appium.java_client.touch.TapOptions.tapOptions;
import static io.appium.java_client.touch.LongPressOptions.longPressOptions;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import static java.time.Duration.ofSeconds;
import static io.appium.java_client.touch.offset.ElementOption.element;
public class UdmeyCode extends Demo4TestBase {
public static void main(String[] args) throws MalformedURLException {
// TODO Auto-generated method stub
AndroidDriver<AndroidElement> driver=Capabilities();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElementByXPath("//android.widget.TextView[#text='Views']").click();
//Tap
TouchAction t =new TouchAction(driver);
WebElement expandList= driver.findElementByXPath("//android.widget.TextView[#text='Expandable Lists']");
t.tap(tapOptions().withElement(element(expandList))).perform();
driver.findElementByXPath("//android.widget.TextView[#text='1. Custom Adapter']").click();
WebElement pn= driver.findElementByXPath("//android.widget.TextView[#text='People Names']");
t.longPress(longPressOptions().withElement(element(pn)).withDuration(ofSeconds(2))).release().perform();
//Thread.sleep(2000);
System.out.println(driver.findElementById("android:id/title").isDisplayed());
}
}
Related
I have below code in eclipse. I am trying to execute it in Chrome. It works fine till clicking on ID #divpaxinfo, but it does not add number of adults. On IE, It does nothing. It just opens the webpage and stops navigating. I have been struggling to know what is the issue, but nothing seems wrong at my end. What could be the issue with?
package testProject2;
import org.openqa.selenium.By;
import org.openqa.selenium.By.ById;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\Users\\bk0107\\Documents\\QA\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://spicejet.com");
driver.findElement(By.id("divpaxinfo")).click();
/*int i=1;
while(i<5)
{
driver.findElement(By.id("hrefIncAdt")).click();//4 times
i++;
}*/
System.out.println(driver.findElement(By.id("divpaxinfo")).getText());
for(int i=1;i<5;i++)
{
driver.findElement(By.id("hrefIncAdt")).click();
}
driver.findElement(By.id("btnclosepaxoption")).click();
System.out.println(driver.findElement(By.id("divpaxinfo")).getText());
}
}
The real problem here is that ChromeDriver is really really fast. As a result it's trying to click on an element before Chrome has finished rendering it and the element is not yet clickable.
The correct solution is to use an explicit wait to wait until the element is clickable, then click on it. You should never mix implicit and explicit waits, so once you have decided to use explicit waits stick with them (they are best practice).
I've added a full set of refactored code, you really only need to add the WebDriver wait and tweak your loop though.
driver.get("http://spicejet.com");
driver.findElement(By.id("divpaxinfo")).click();
System.out.println(driver.findElement(By.id("divpaxinfo")).getText());
WebDriverWait wait = new WebDriverWait(driver, 15, 50);
for (int i = 1; i < 5; i++) {
wait.until(ExpectedConditions.elementToBeClickable(By.id("hrefIncAdt"))).click();
}
driver.findElement(By.id("btnclosepaxoption")).click();
System.out.println(driver.findElement(By.id("divpaxinfo")).getText());
This explicitly waits for the element that you want to click on to be clickable before you click on it, this is a better check than visibility because an element can be visible, but not clickable.
Add Implicit wait and browser maximize code Just after creating instance of driver as follows :
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.manage().window().maximize();
Suggestion : Add some wait(implicit/fluent) in script for proper execution
Your Program with improvements :
package practice;
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.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
public class Program1 {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","src\\main\\resources\\drivers\\win\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://spicejet.com");
WebDriverWait wait=new WebDriverWait(driver, 20);
WebElement element =wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("divpaxinfo")));
element.click();
System.out.println(driver.findElement(By.id("divpaxinfo")).getText());
WebElement element1 =wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("hrefIncAdt")));
for(int i=1;i<5;i++){
element1.click();
}
driver.findElement(By.id("btnclosepaxoption")).click();
System.out.println(driver.findElement(By.id("divpaxinfo")).getText());
}
}
Please Find the below code: I have performed the following steps, but didn't worked.
Please Help:
public class ForSe_TestCases
public WebDriver driver;
#BeforeTest
public void setup ()
{
System.setProperty("webdriver.chrome.driver", "path");
WebDriver driver =new ChromeDriver();
driver.manage().deleteAllCookies();
}
#Test(priority = 0)
public void Validlogin_IO () throws InterruptedException {
driver.navigate().to("http://**URL**");
driver.findElement(By.xpath("//*[#id='email_address']")).sendKeys("tengku.forse#gmail.com");
driver.findElement(By.xpath("//*[#id='password']")).sendKeys("Pass12345");
driver.findElement(By.xpath("//*[#id='login-form']/div[4]/button")).click();
System.out.println("Login button pressed");
}
What can be the issue with TestNG ?
Try any/all of the following
Remove and Add TestNG jar again to ur project build path
UNinstall and reinstall the TestNG plugin
Clean the Eclipse project amd rerun.
If nothing works try this :
public static void main(String[] args) {
TestListenerAdapter tla = new TestListenerAdapter();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { YOURCLASSNAME.class });
testng.addListener(tla);
testng.run();
}
In place of YOURCLASSNAME give the classname that contains the #Test annotations. This is like running your testing without the plugin from main method.
Sanchit, I think it fails because you are not waiting for the element to appear on the page and the webDriver (which is faster than its shadow!) thinks the first element you are trying to locate isn't there (id='email_address).
Try reading here for implicit or explicit way to wait or use this code of mine below instead (if the element is present then the method returns true):
public boolean waitForElement(String elementXpath, int timeOut) {
try{
WebDriverWait wait = new WebDriverWait(driver, timeOut);
boolean elementPresent=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(elementXpath)).isDisplayed());
System.out.printf("%nElement is present [T/F]..? ")+elementPresent;
}
catch(TimeoutException e1){e1.printStackTrace();elementPresent=false;}
return elementPresent;
}
Update after OP's comments
To see if my method works, try replacing your first find element line:
driver.findElement(By.xpath("//*[#id='email_address']")).sendKeys("tengku.forse#gmail.com"); //this is official email
with this code below instead (then your script won't break from then ownwards, if it does use this waiting method again for the 'breaking' element). I think your script is breaking straight away because you locate the element and sendKeys very fast without waiting for it to appear first!
waitForElement ("//*[#id='email_address']", 10);
if(elementPresent==true){
driver.findElement(By.xpath("//*[#id='email_address']")).sendKeys("tengku.forse#gmail.com");
}
else{
System.out.println("FATAL! Couldn't locate email address field!");
}
Hope you can crack it this time round!
Update to Chrome driver 2.28, Google Chrome to 57.x and Selenium to 3.x.x You also have to set the path of the Chrome driver before you open the browser.
package demo;
import java.util.concurrent.TimeUnit;
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.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class TestAnyURL_TestNG
{
WebDriver driver;
#BeforeTest
public void setup ()
{
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("--js-flags=--expose-gc");
options.addArguments("--enable-precise-memory-info");
options.addArguments("--disable-popup-blocking");
options.addArguments("--disable-default-apps");
options.addArguments("test-type=browser");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().deleteAllCookies();
}
#Test(priority = 0)
public void Validlogin_IO () throws InterruptedException
{
driver.navigate().to("http://google.com"); //ForSe test environment URL
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[#id='email_address']")).sendKeys("tengku.forse#gmail.com"); //this is official email
driver.findElement(By.xpath("//*[#id='password']")).sendKeys("Pass12345"); //this is password
driver.findElement(By.xpath("//*[#id='login-form']/div[4]/button")).click(); //click on submit button to login
System.out.println("Login button pressed"); } //This code is to add new case
#Test (priority = 1)
public void AddCase() throws InterruptedException
{
WebElement element = driver.findElement(By.partialLinkText("Add Case")); //To find 'Add Case' button on dashboard
Actions action = new Actions (driver); action.moveToElement(element); //Move mouse and hover to 'Add Case' button
action.click().build().perform(); //Click on 'Add Case' button
driver.findElement(By.id("name")).sendKeys("Perak Murder Case -53311");//Provide Case Name
driver.findElement(By.id("fileupload")).sendKeys("C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\FisheyeImages\\IMG_1187.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\FisheyeImages\\IMG_1188.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\FisheyeImages\\IMG_1189.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\Fisheye Images\\IMG_1190.JPG"); //Upload files
driver.findElement(By.id("fileupload1")).sendKeys("C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\EvidenceImages\\_DSC0970.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSI>Images\\EvidenceImages\\_DSC0971.JPG"+"\n"+"C:\\Users\\sanchit.IGENEDC\\Desktop\\iCSIImages\\Evidence Images\\_DSC0972.JPG");
Thread.sleep(6000); //wait for files to load
driver.findElement(By.id("btnSubmit")).click();//click on submit button
}
}
Check this code. This code successfully opens the google.co.in
Execute this file "Run As TestNG Test"
Let me know if this helps you.
I am trying to use the click(WebElement) method of the Actions class to click on an element on the google homepage. The code runs successfully but the click event is not trigerred.
package p1;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
public class ClickLink
{
static WebDriver driver;
public static void main(String[] args)
{
try
{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.google.com/");
WebElement icon = driver.findElement(By.xpath(".//*[#id='gbwa']/div[1]/a"));
Actions ob = new Actions(driver);
ob.click(icon);
System.out.println("Link Clicked !!");
Thread.sleep(10000);
driver.close();
}
catch(Exception e)
{
System.out.println("Exception occurred : "+e);
driver.close();
}
}
}
Here is the result when the above script is executed : [link]
However, when the same element is clicked using the click() method of the WebElement interface, then the click is trigerred.
package p1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
public class ClickLink
{
static WebDriver driver;
public static void main(String[] args)
{
try
{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.google.com/");
WebElement icon = driver.findElement(By.xpath(".//*[#id='gbwa']/div[1]/a"));
icon.click();
System.out.println("Link Clicked !!");
Thread.sleep(10000);
driver.close();
}
catch(Exception e)
{
System.out.println("Exception occurred : "+e);
driver.close();
}
}
}
Here is the result when the above script is executed : [link]
Please let me know the reason as to why the click event is not trigerred and resolution for the same.
You have made a simple mistake of not building and performing the Action.
Note that you have created an instance of Actions class ob. As the name signifies the Actions class defines a set of sequential actions to be performed. So you have to build() your actions to create a single Action and then perform() the action.
The below code should work!!
WebElement icon = driver.findElement(By.xpath(".//*[#id='gbwa']/div[1]/a"));
Actions ob = new Actions(driver);
ob.click(icon);
Action action = ob.build();
action.perform();
If you look at the code given below to first move to the icon element and then click the element would better explain the Actions class.
Actions ob = new Actions(driver);
ob.moveToElement(icon);
ob.click(icon);
Action action = ob.build();
action.perform();
Here is what you need to do:
ob.click(icon).build().perform();
also you can do this:
ob.moveToElement(icon).click().build().perform();
In web automation, this issue keeps coming. Reasons can be multiple. Let's see them one by one :
Actions class not properly utilized :
Link to Official documentation
As the method documentation says,
Call perform() at the end of the method chain to actually perform the actions.
The general way to achieve click using Actions class is below :
actionsObj.moveToElement(element1).click().build().perform()
If Actions class fails , sometimes the reason can be that you receive below exception :
ElementNotInteractableException [object HTMLSpanElement] has no size and location
That can mean two things :
a. Element has not properly rendered: Solution for this is just to use implicit /explicit wait
Implicit wait :
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
Explicit wait :
WebDriverWait wait=new WebDriverWait(driver, 20);
element1 = wait.until(ExpectedConditions.elementToBeClickable(By.className("fa-stack-1x")));
b. Element has rendered but it is not in the visible part of the screen: Solution is just to scroll till the element. Based on the version of Selenium it can be handled in different ways but I will provide a solution that works in all versions :
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].scrollIntoView(true);", element1);
Suppose all this fails then another way is to again make use of Javascript executor as following :
executor.executeScript("arguments[0].click();", element1);
If you still can't click , then it could again mean two things :
1. Iframe
Check the DOM to see if the element you are inspecting lives in any frame. If that is true then you would need to switch to this frame before attempting any operation.
driver.switchTo().frame("a077aa5e"); //switching the frame by ID
System.out.println("********We are switching to the iframe*******");
driver.findElement(By.xpath("html/body/a/img")).click();
2. New tab
If a new tab has opened up and the element exists on it then you again need to code something like below to switch to it before attempting operation.
String parent = driver.getWindowHandle();
driver.findElement(By.partialLinkText("Continue")).click();
Set<String> s = driver.getWindowHandles();
// Now iterate using Iterator
Iterator<String> I1 = s.iterator();
while (I1.hasNext()) {
String child_window = I1.next();
if (!parent.equals(child_window)) {
driver.switchTo().window(child_window);
element1.click()
}
When I try to run my code, it only shows cucumber skeleton. I use a JUnit runner class as JUnit test suite.
Code is below for all three classes.
Feature is :
Feature: Check addition in Google calculator
In order to verify that google calculator work correctly
As a user of google
I should be able to get correct addition result
#Runme
Scenario: Addition
Given I open google
When I enter "2+2" in search textbox
Then I should get result as "4"
Selenium Class :
package cucumberTest;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumTest {
private SeleniumTest()
{
}
private static WebDriver driver = null;
public static void seleniumTest() {
// Create a new instance of the Firefox driver
driver = new FirefoxDriver();
//Put a Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch the Online Store Website
driver.get("http://www.store.demoqa.com");
// Find the element that's ID attribute is 'account'(My Account)
driver.findElement(By.xpath(".//*[#id='account']/a")).click();
// Find the element that's ID attribute is 'log' (Username)
// Enter Username on the element found by above desc.
driver.findElement(By.id("log")).sendKeys("testuser_1");
// Find the element that's ID attribute is 'pwd' (Password)
// Enter Password on the element found by the above desc.
driver.findElement(By.id("pwd")).sendKeys("Test#123");
// Now submit the form. WebDriver will find the form for us from the element
driver.findElement(By.id("login")).click();
// Print a Log In message to the screen
System.out.println("Login Successfully");
// Find the element that's ID attribute is 'account_logout' (Log Out)
driver.findElement (By.xpath(".//*[#id='account_logout']/a")).click();
// Print a Log In message to the screen
System.out.println("LogOut Successfully");
// Close the driver
driver.quit();
}
}
JUnit Class:
package cucumberTest;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
//#CucumberOptions(
// features = "Feature/googleCalc.feature"
////,glue={"stepDefinition"}
// )
#CucumberOptions(
features = {"Feature/googleCalc.feature"},glue={"stepDefinition"},
plugin = {"pretty"},
tags = {"#Runme"}
)
public class TestRunner {
}
Step Definitions :
package stepDefination;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumberTest.SeleniumTest;
public class googleCalcStepDefinition {
#Given("^I open google$")
public void i_open_google() throws Throwable {
// Write code here that turns the phrase above into concrete actions
SeleniumTest.seleniumTest();
}
#When("^I enter \"(.*?)\" in search textbox$")
public void i_enter_in_search_textbox(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
SeleniumTest.seleniumTest();
}
#Then("^I should get result as \"(.*?)\"$")
public void i_should_get_result_as(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
SeleniumTest.seleniumTest();
}
}
Output shown is :
Feature: Check addition in Google calculator
In order to verify that google calculator work correctly
As a user of google
I should be able to get correct addition result
#Runme
Scenario: Addition [90m# Feature/googleCalc.feature:7[0m
[33mGiven [0m[33mI open google[0m
[33mWhen [0m[33mI enter "2+2" in search textbox[0m
[33mThen [0m[33mI should get result as "4"[0m
1 Scenarios ([33m1 undefined[0m)
3 Steps ([33m3 undefined[0m)
0m0.000s
You can implement missing steps with the snippets below:
#Given("^I open google$")
public void i_open_google() throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#When("^I enter \"(.*?)\" in search textbox$")
public void i_enter_in_search_textbox(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
#Then("^I should get result as \"(.*?)\"$")
public void i_should_get_result_as(String arg1) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
I found the reason it was not executing because i added Selenium test class and Junit runner class in Package cucumberTest; and skeleton was in package stepDefination; so what i did was i moved skeleton to pacakge cucumberTest; where junit runner and selenium classes are it resolved the issue for . Issue was occuring because when you place Junit class in package it will search for skeleton in that package but if you add JUnit runner class in source folder then it will be able to find the page under src folder
Hi I am new to Webdriver and Junit. Need this puzzle solved. I did a lot of research but couldnt find the one that could help.
So I declared my driver up top as Static Webdriver fd and then trying to run cases on single class files (also tried multiple class files) but everytime I run the browser launches twice. I can seem to debug this problem please help. Here is my code:
package Wspace;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class Wsinventory {
static WebDriver fd;
#Rule
public static ErrorCollector errCollector = new ErrorCollector();
#Before
public void openFirefox() throws IOException
{
System.out.println("Launching WebSpace 9.0 in FireFox");
ProfilesIni pr = new ProfilesIni();
FirefoxProfile fp = pr.getProfile("ERS_Profile"); //FF profile
fd = new FirefoxDriver(fp);
fd.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
fd.get("http://www.testsite.com");
fd.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
String ffpagetitle = fd.getTitle(); //ffpagetitle means firefox page title
//System.out.println(pagetitle);
try{
Assert.assertEquals("Webspace Login Page", ffpagetitle);
}catch(Throwable t){
System.out.println("ERROR ENCOUNTERED");
errCollector.addError(t);
}
}
#Test
public void wsloginTest(){
fd.findElement(By.name("User ID")).sendKeys("CA");
fd.findElement(By.name("Password")).sendKeys("SONIKA");
fd.findElement(By.name("Logon WebSpace")).click();
}
#Test
public void switchtoInventory() throws InterruptedException{
Thread.sleep(5000);
fd.switchTo().frame("body"); //Main frame
fd.switchTo().frame("leftNav"); //Sub frame
fd.findElement(By.name("Inventory")).click();
fd.switchTo().defaultContent();
fd.switchTo().frame("body");
}
}
The problem is that your #Before method is running before every test. When you run your second test, it is calling that method again, and throwing away that old instance of FirefoxDriver, and creating a new one (stored in that static instance of driver).
Use #BeforeClass instead.