Junit/Webdriver - Why my browser is launching twice - selenium

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.

Related

Selenium Web Driver code with Java not navigating the website

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());
}
}

My scrip works fine in java class but same script fails when I use testng. It just opens the browser and fails my script

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.

LeanFT and Selenium Compatibility?

I would like to know if Selenium and LeanFT can play nicely together. I don't know if anyone has tried to do this yet, but I think if it can work, LeanFT can provide some supplementary benefits to the selenium framework.
As I understand it currently, the limitations of Selenium are:
Selenium MUST open the initial browser to recognize it
Selenium MUST open all popups to recognize them.
Selenium WebDriver may become stale while waiting for non-Selenium procedures.
I have attempted the object flow UML for both HP's suggested model and my own idea of how this might work.
The Control flow would be something like:
#Before -> globalSetup (LeanFT init)
#BeforeClass -> testSetup (LeanFT init)
#BeforeClass -> getSeleniumDriver (Selenium)
#Test -> some selenium procedures
/**** To prevent Selenium from dying. ****/
#Test -> new Thread -> run leanFTsnippet1()
#Test -> resume selenium final steps..
#After -> reporting, closing Webdriver
Here is some of my current code from an example Test Class.
#BeforeClass
public static void beforeLFTClass() throws Exception {
globalSetup(CoreFunctionality.class);
}
#AfterClass
public static void afterLFTClass() throws Exception {
globalTearDown();
}
#Test
public void runLeanFtThread() {
// put selenium code here
// ...
// begin leanft part of test
Thread leanftThread = new Thread( new Runnable() {
#Override
public void run() {
try {
test();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
leanftThread.start();
try {
leanftThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void test() throws Exception {
//Starting Browser
Browser browser = BrowserFactory.attach(new BrowserDescription.Builder().title(driver.getTitle()).build());
Assert.assertEquals(browser.getTitle(), driver.getTitle());
}
Anyways, its a pretty interesting problem. Would really love to see what you guys think.
Thanks!
They indeed play nicely together. I have been using them in my scripts and I like to utilize the powers of each tool. What I have done is create a LeanFT test template and add the Selenium libraries to it.
Here is a sample code:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using HP.LFT.SDK;
using HP.LFT.SDK.Web;
using Search_Regression_Test;
using TestAutomationReporting;
using UnifiedFramework;
using System.Configuration;
using System.Diagnostics;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using Selenium = OpenQA.Selenium;
namespace Search_Regression_Test
{
[TestClass]
public class LeanFtTest : UnitTestClassBase<LeanFtTest>
{
static IBrowser browser;
static IWebDriver chromeDriver;
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
GlobalSetup(context);
ChromeOptions CO = new ChromeOptions();
CO.AddExtension(#"C:\Program Files (x86)\HP\LeanFT\Installations\Chrome\Agent.crx");
chromeDriver = new ChromeDriver(CO);
chromeDriver.Manage().Window.Maximize();
browser = BrowserFactory.Attach(new BrowserDescription
{
Type = BrowserType.Chrome
});
.... and so on.
The new Version of LeanFT (14) even brings some explicit Selenium-integration: You can select Selenium as your automation SDK in the project creation wizard, there is a Selenium-specific Object Identification Center, and some additional locators and utilities. Full story here: LeanFT for Selenium.
I'm not entirely sure why this question doesn't have an accepted answer yet, but I'm going to take a stab at answering this with a sample that highlights once more that LeanFT and Selenium are playing nicely together
It's written in Java. Probably it can be optimized a bit, but it should clearly show how you can achieve simultaneous interaction with the same browser.
(The Java Project was created from LeanFT templates. UnitTestClassBase class comes from there. It basically initializes LeanFT and the reporter behind the scenes. To get around it if you don't want to use it you'd have to call SDK.init(), Reporter.init(), Reporter.generateReport() and SDK.cleanup() as needed - check the docs for details)
The AUT used is advantage shopping: http://advantageonlineshopping.com/
package com.demo;
import static org.junit.Assert.*;
import java.io.File;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.Keys;
import org.openqa.selenium.chrome.*;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.hpe.leanft.selenium.By;
import com.hp.lft.report.Reporter;
import com.hp.lft.report.Status;
import com.hp.lft.sdk.web.*;
import com.hp.lft.verifications.Verify;
public class SeleniumTest extends UnitTestClassBase {
private ChromeDriver chromeDriver;
private Browser browser;
public SeleniumTest() {
System.setProperty("webdriver.chrome.driver",this.getClass().getResource("/chromedriver.exe").getPath());
}
#BeforeClass
public static void setUpBeforeClass() throws Exception {
instance = new SeleniumTest();
globalSetup(SeleniumTest.class);
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
globalTearDown();
}
#Before
public void setUp() throws Exception {
// SELENIUM: Construct and launch the browser with LeanFT agent
ChromeOptions options = new ChromeOptions();
File paths = new File("C:\\Program Files (x86)\\HP\\LeanFT\\Installations\\Chrome\\Agent.crx");
options.addExtensions(paths);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
chromeDriver = new ChromeDriver(options);
}
#After
public void tearDown() throws Exception {
// LEANFT: close the browser opened by selenium
browser.close();
}
#Test
public void test() throws Exception {
// SELENIUM: Go to the Advantage shopping website and maximize it
chromeDriver.get("http://156.152.164.67:8080/#/");
chromeDriver.manage().window().maximize();
// LEANFT: Attach to the browser
browser = BrowserFactory.attach(new BrowserDescription.Builder()
.type(BrowserType.CHROME).openTitle(" Advantage Shopping")
.build());
// LEANFT: Click on tablets button
browser.describe(WebElement.class, new WebElementDescription.Builder()
.className("categoryCell").tagName("DIV").innerText("TABLETS Shop Now ").build()).click();
// SELENIUM: Expand the display section after it was seen
(new WebDriverWait(chromeDriver, 10))
.until(new ExpectedCondition<org.openqa.selenium.WebElement>(){
#Override
public org.openqa.selenium.WebElement apply(org.openqa.selenium.WebDriver d) {
return d.findElement(By.cssSelector("h4#accordionAttrib0"));
}}).click();
// LEANFT: select the preferred display size, click the preferred tablet and add the tablet to the cart
browser.describe(CheckBox.class, new CheckBoxDescription.Builder()
.type("checkbox").role("").accessibilityName("").tagName("INPUT").name("").index(1).build()).set(true);
browser.describe(Image.class, new ImageDescription.Builder()
.alt("").type(com.hp.lft.sdk.web.ImageType.NORMAL).tagName("IMG").index(1).build()).click();
browser.describe(Button.class, new ButtonDescription.Builder()
.buttonType("submit").tagName("BUTTON").name("ADD TO CART").build()).click();
// SELENIUM: go to cart
chromeDriver.get("http://156.152.164.67:8080/#/shoppingCart");
// LEANFT: checkout
browser.describe(Button.class, new ButtonDescription.Builder()
.buttonType("submit").tagName("BUTTON").name("CHECKOUT ($1,009.00)").build()).click();
// SELENIUM: Register as a new user after the button was seen
(new WebDriverWait(chromeDriver, 10))
.until(new ExpectedCondition<org.openqa.selenium.WebElement>(){
#Override
public org.openqa.selenium.WebElement apply(org.openqa.selenium.WebDriver d) {
return d.findElement(By.xpath("//DIV[#id=\"newClient\"]/DIV[1]/SEC-FORM[1]/SEC-SENDER[1]/BUTTON[#role=\"button\"][1]"));
}}).click();
// LEANFT: fill in the user name and email
String username = "U" + Calendar.getInstance().getTimeInMillis(); // unique name each time
browser.describe(EditField.class, new EditFieldDescription.Builder()
.type("text").tagName("INPUT").name("userName").build()).setValue(username);
browser.describe(EditField.class, new EditFieldDescription.Builder()
.type("text").tagName("INPUT").name("userEmail").build()).setValue("myuser_email#emailsite.org");
// SELENIUM: Set password and confirm password
chromeDriver.findElementByXPath("//SEC-VIEW/DIV[normalize-space()=\"*Password\"]/INPUT[1]").sendKeys("Password1");
chromeDriver.findElementByXPath("//SEC-VIEW/DIV[normalize-space()=\"*Confirm password\"]/INPUT[1]").sendKeys("Password1");
// LEANFT: check the 'I agree' checkbox and register, then click on next shipping details.
browser.describe(CheckBox.class, new CheckBoxDescription.Builder()
.type("checkbox").tagName("INPUT").name("registrationAgreement").build()).set(true);
browser.describe(Button.class, new ButtonDescription.Builder()
.buttonType("button").tagName("BUTTON").name("REGISTER").build()).click();
browser.describe(Button.class, new ButtonDescription.Builder()
.buttonType("submit").tagName("BUTTON").name("NEXT").build()).click();
// SELENIUM: confirm the user name and pass
chromeDriver.findElementByXPath("//DIV[#id=\"paymentMethod\"]/DIV/DIV/SEC-FORM/SEC-VIEW/DIV[normalize-space()=\"*SafePay username\"]/INPUT[1]").sendKeys(username);
chromeDriver.findElementByXPath("//DIV[#id=\"paymentMethod\"]/DIV/DIV/SEC-FORM/SEC-VIEW/DIV[normalize-space()=\"*SafePay password\"]/INPUT[1]").sendKeys("Password1");
// LEANFT: click "Pay now" and confirm payment was done
browser.describe(Button.class, new ButtonDescription.Builder()
.buttonType("button").role("button").accessibilityName("").tagName("BUTTON").name("PAY NOW").index(0).build()).click();
Verify.isTrue(
browser.describe(WebElement.class, new WebElementDescription.Builder()
.tagName("SPAN").innerText("Thank you for buying with Advantage").build())
.exists());
}
}

Long press on AndroidElement in Appium

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());
}
}

Cucumber not running selenium Code

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