Appium android buttons strange working - java

I have problem with testing my app which is intended for online shopping. I noticed that all buttons from application working but I have problem with system buttons(look at the picture). I’m using to recognize the button UiAutomatorViewer.
At the picture I’m trying add product to cart but when I’m click button “Dodaj”(means Add) the window closes but there are any actions in application, the product should be added to cart. I tested this application manually and everything work correct.
I tried to operate the button in many ways but still nothing. Does anyone know how to solve it? It’s very important functions to testing for me.
public class Product extends MainPage {
private AndroidDriver<AndroidElement> driver;
#FindBy(id = "com.mec.leroy:id/product_add_to_cart")
private WebElement addToCart;
#FindBy(xpath = "//android.widget.Button[#index='1']") //problem with button
private WebElement buttonAdd;
#FindBy(id = "com.mec.leroy:id/product_name")
private WebElement productName;
public Product(AndroidDriver driver) {
super(driver);
this.driver = driver;
}
public Product addProduct() throws InterruptedException {
driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector()).scrollIntoView(text(\"do koszyka\"));");
addToCart.click();
buttonAdd.click();
Thread.sleep(5000);
return new Product(driver);
}
public boolean productName() throws InterruptedException {
Thread.sleep(2000);
try {
productName.getText();
return true;
} catch (ElementNotVisibleException e) {
return false;
}
}
public class Connector {
public AndroidDriver Settings() throws IOException, InterruptedException {
runAppium();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "33004db396a6c2d1"); // nazwa urządzenia
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "UiAutomator2");
capabilities.setCapability("noRest", "true");
capabilities.setCapability("fullReset", "false");
// capabilities.setCapability("useKeystore", "true");
//uruchomienie aplikacji z poziomu telefonu
capabilities.setCapability("appPackage", "com.mec.leroy");
capabilities.setCapability("appActivity", "com.mec.leroy.main.activity.MainActivity");
//inicjalizacja połączenia z Appium Server
AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);
return driver;
}

You are using UiAutomatorViewer (that uses old UiAutomator), but in your tests you are providing UiAutomator2: important to know that these frameworks build snapshot xml in a different way, so your locator might be incorrect.
I suggest to try inspect and interact with your button using official appium-desktop:
Install & launch it
Run the server via appium-desktop
Set exact the same capabilities you have in the code, create new session
Now you can inspect your elements and try to click your button from inspector.

Related

How to resolve the issue with the browser is being closed when start running testng using Edge driver

I have a couple issues when I run the test with edge web browser.
The first issue is that every time I run the test by run as > testng test , the automation will close all the existing open edge web browser and then it will open a brand new edge browser but it is blank (could not load the url)
The second issue is that the automation would only load the url if I manually close all of the existing edge browser.
Is there a way to fix these issues? please help me thank you in advance.
Here is my code
public class OpenThePageUsingEdge {
public String baseUrl = "https://catalog-qa.baylorgenetics.com/search";
String driverPath = "C:\\Eclipse\\MicrosoftWebDriver.exe";
public WebDriver driver ;
//initiate NameofInsured as the GenerateData class
//GenerateData NameOfAddrecipients;
#BeforeTest
public void setup(ITestContext ctx) {
TestRunner runner = (TestRunner) ctx;
runner.setOutputDirectory("J:\\zzQA Selenium Automation Suite\\Test Results");
}
#Test
public void openThePageusingEdge () throws InterruptedException {
System.out.println("launching Edge browser");
System.setProperty("webdriver.edge.driver", driverPath);
driver = new EdgeDriver();
driver.get(baseUrl);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Why is my selenium webdriver opening blank windows of "data;"

I'm trying to set up my webdriver so that it can execute tests in parallel from the xml sheet, this it does, but I find sometimes it opens up blank chrome windows of "data;"
I've researched around other questions and all the answers seem to say things about putting the webdriver as a new threadlocal<RemoteWebDriver>, which I am already doing.
This is the WebDriverSetup.java file I am using:
public class WebDriverSetup {
private static ThreadLocal<RemoteWebDriver> threadDriver = null;
public WebDriver driver(){
return threadDriver.get();
}
#BeforeMethod
public void setUp() throws MalformedURLException {
//Set up the path to the chromedriver so that the user will not have problems if they don't have the system path variable set up.
System.setProperty("webdriver.chrome.driver", TestExecutor.projectDirectory + "/chromedriver.exe");
//Set the hub URL
String seleniumUrl = "http://" + TestExecutor.hubUrl + "/wd/hub";
//Turn off logging because as of selenium-standalone-server-3.0.1, there
//is an "INFO" message that appears in console that could be mistaken for
//an error message.
Logger.getLogger("org.openqa.selenium.remote").setLevel(Level.OFF);
//threadDriver needs to be on its own local thread
threadDriver = new ThreadLocal<RemoteWebDriver>();
//Set chromeoptions so they open headless on the VM, but the VM imagines the
//tests as if chrome was running full screen on a desktop session.
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--window-size=1920,1080");
//Apply the options to the chromedriver session.
URL seleniumHubURL = new URL(seleniumUrl);
threadDriver.set(new RemoteWebDriver(seleniumHubURL, options));
}
}
and this is how I am calling it from my test:
public class Demo_1_Filter_Users_By_Firstname extends TestBase.ClassGlobals
{
private WebDriverSetup webDriverSetup;
private EventFiringWebDriver driver;
private File logFile;
#Test
public void main(){
//The main method
driver.get("web_application_url");
}
#BeforeMethod
public void testSetup() throws IOException {
//Setup the webdriver
webDriverSetup = new WebDriverSetup();
driver = new EventFiringWebDriver( webDriverSetup.driver() );
//Set up an eventhandler on the event so that all the logging functions work
EventHandler handler = new EventHandler();
driver.register( handler );
//Setup the logfile
logFile = commonMethods.newLogFile();
//Log
commonMethods.log(logFile, "------TEST STARTED------");
}
#AfterMethod
public void testClosure(){
//Close webdriver session, log test done etc
}
}
The error that I am experiencing doesn't happen every time, and I don't understand why the window is hanging on data; even though the first line of my main method is to create a new webdriver session, and then using that session, open the web application through driver.get()
I am using chromedriver version 2.41
The latest stable version of ChromeDriver (88.0.4324.96) appears to have fixed this:
Resolved issue 3641: Page not getting loaded/rendered when browser window is not in focus with Chrome Beta v87 and chromedriver v(87/86)
I've been having this issue for a while and updating my chromedriver.exe file finally solved it.

Illegal Argument Exception in Appium framework

After (foolishly) upgrading Appium Server along with various project libraries, such that I cannot tell which, if any, caused the problem, my previously running Appium framework suddenly started failing upon attempting to locate any elements.
The server starts (either manually via desktop or through the java code) and it launches my emulator (if not already loaded), makes the connection, opens the app (in the case show, simply settings) and fails as soon as it tries to validate that the settings main page is displayed by checking the existence of the "Settings" text:
Given the settings app is displayed (FAILED)
(java.lang.IllegalArgumentException: Can not set
io.appium.java_client.android.AndroidElement field
com.mindtree.pageobjects.SettingsMainPage.header to
org.openqa.selenium.remote.RemoteWebElement$$EnhancerByCGLIB$$d27c0df4)
The Appium server versions for both desktop and nodeJS is currently 1.7.2 I believe the problem started when I was originally at 1.7.1 or 1.7.2 and it succeeded in doing an auto-update on the desktop version to 1.8.1.
Selenium version is 3.11.0 (tried various flavors from 3.9.0 through 3.13.0)
Appium Java client is 6.0.0-BETA5 (tried 6.0.0-BETA4, 6.0.0, 6.1.0)
Java is 1.8
The JBehave test step that reports the error:
#Given("the settings app is displayed")
public void givenTheSettingsAppIsDisplayed() {
main = new SettingsMainPage(driver);
if (main.pageLoaded())
test.logGivenPass("the settings app is displayed");
else {
test.logGivenFail("the settings app is displayed");
fail();
}
}
The corresponding page object snippet:
public class SettingsMainPage extends MobilePageObject {
public SettingsMainPage(AndroidDriver<AndroidElement> driver) {
super(driver);
System.out.println("Settings Main page class has been initialized");
}
#AndroidFindBy(xpath = "//android.widget.TextView[#text='Settings']")
AndroidElement header;
#AndroidFindBy(id= "android:id/title")
List<AndroidElement> titles;
#AndroidFindBy(id= "android:id/summary")
List<AndroidElement> summaries;
public Boolean pageLoaded() {
return helper.isDisplayed(header);
}
}
Googling this particular error returns a few hits, but no offered solutions.
Any guidance appreciated.
edit: I should add that the failure seems to happen upon initialization of the page object via the page factory, since the text "initialized" is never shown, it fails while trying to initialize all the page elements, specifically the first one, at least according to the error message.
My base page object is below:
import java.time.Duration;
import org.openqa.selenium.support.PageFactory;
import com.mindtree.helpers.AppiumUtils;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.pagefactory.AppiumFieldDecorator;
public class MobilePageObject {
AndroidDriver<AndroidElement> driver;
AppiumUtils helper;
public MobilePageObject(AndroidDriver<AndroidElement> driver) {
this.driver = driver;
PageFactory.initElements(new AppiumFieldDecorator(driver, Duration.ofSeconds(15)), this);
helper = new AppiumUtils();
}
}
Edit Update: Downgraded the Appium Server through NodeJS from 1.7.2 to
1.7.1. Result: no change, same error reported.
I am using Appium server 1.8.1, selenium 3.13.0 and java client 6.1.0. I use the page object model like following and it works fine.
public class SettingsMainPage{
public SettingsMainPage(AndroidDriver<AndroidElement> driver) {
PageFactory.initElements(new AppiumFieldDecorator(driver), this);
System.out.println("Settings Main page class has been initialized");
}
#AndroidFindBy(xpath = "//android.widget.TextView[#text='Settings']")
AndroidElement header;
#AndroidFindBy(id= "android:id/title")
List<AndroidElement> titles;
#AndroidFindBy(id= "android:id/summary")
List<AndroidElement> summaries;
public boolean pageLoaded() {
try{
(new WebDriverWait(driver, 20)).until(ExpectedConditions.visibilityOfElementLocated(header));
return header.isDisplayed();
}
catch(Exception e){
return false;
}
}
}
And you must define your desiredCapabilities like following:
public static AppiumDriver<MobileElement> driver;
public static AppiumDriver<MobileElement> setupDesiredCapabilities(String appPackage, String appActivity,
String udid, String platformVersion, boolean noReset) {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("deviceName", "Android phone"); //any name
caps.setCapability("udid", udid);
caps.setCapability("platformName", "Android");
caps.setCapability("platformVersion", platformVersion);
caps.setCapability("appPackage", appPackage);
caps.setCapability("appActivity", appActivity);
caps.setCapability("noReset", noReset); //optional
try {
driver = new AndroidDriver<MobileElement>(new URL(
"http://127.0.0.1:4723/wd/hub"), caps);
} catch (MalformedURLException e) {
//
} catch (Exception ex) {
//
}
return driver;
}
Make sure you have define static AppiumDriver and use the same
driver object to call constructor of each page.

NullPointerException when running my test with page factory

I get an exception when I run my test. I am using selenium with page factory. When I run following code ,it will open up the website and fail with exception below. it doesn't perform the HomePage.ClickbtnCookieWarning() in my test case.
Can someone please help me to understand why my code isn't working?
FAILED CONFIGURATION: #BeforeTest SetUp java.lang.NullPointerException
at
org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at
org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy5.click(Unknown Source) at
pageObjects.HomePage.ClickLoginLink(HomePage.java:57) at
myaccountsuite.TC1DefaultDeliveryAddDisplay.SetUp(TC1DefaultDeliveryAddDisplay.java:29)
Home Page page object
public class HomePage {
WebDriver driver;
public HomePage (WebDriver driver)
{
this.driver=driver;
}
#FindBy(id="ctl00_header_hdrCookieWarning_btnHideCookieWarning")
WebElement btnCookieWarning;
#FindBy(xpath=".//*#id='ctl00_masterContainerTop_Block_637_LoginView1_ulAnonymous']/li[2]/a")
WebElement LoginLink;
public void ClickbtnCookieWarning()
{
btnCookieWarning.click();
}
public void ClickLoginLink()
{
LoginLink.click();
}
}
Login Page Object
public class login {
WebDriver driver;
public login(WebDriver driver)
{
this.driver = driver;
}
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_UserName")
WebElement UserName;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_Password")
WebElement Password;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_LoginButton")
WebElement btn_LogIn;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_txtAccount")
WebElement Account;
#FindBy(id="ctl00_ContentPlaceHolderMain_container_container_Block_166_lgn1_btnHomeBranch_3")
WebElement btn_Continue;
public void userLogin(String uname, String pass, String acc)
{
UserName.sendKeys(uname);
Password.sendKeys(pass);
btn_LogIn.click();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
Account.sendKeys(acc);
btn_LogIn.click();
btn_Continue.click();
}
}
My Test
public class TC1DefaultDeliveryAddDisplay {
public WebDriver driver;
#BeforeTest(alwaysRun = true)
public void SetUp() {
HomePage HomePage = PageFactory.initElements(driver, HomePage.class);
login loginpage = PageFactory.initElements(driver, login.class);
driver = new FirefoxDriver();
driver.get("http://URL/");
HomePage.ClickbtnCookieWarning();
HomePage.ClickLoginLink();
loginpage.userLogin("aa#yahoo.com", "125", "Test");
}
You're getting NullPointerException because you're using WebDriver instance before initialising.
You need to Initialize WebDriver before using this instance as :-
driver = new FirefoxDriver();
HomePage HomePage = PageFactory.initElements(driver, HomePage.class);
Login loginpage =PageFactory.initElements(driver, login.class);
If you want to use WebDriver as singleton which returns single instance for all your test methods you can follow this answer which is exactly you want.
The problem is in each class you are creating new instance of driver. You just need to create one driver instance in you base class where you do your browser setup. Please refer Page Object Model. Once the Driver instance is created you need to use the same in all your classes. Or else it will throw NullPointerException because driver will not have any reference.

Appium startActivity() Function

I am new to Appium, In my code I have given required desired capabilities and wrote one test case that is working fine. Now I want to launch another App for second test in same code , how can I do that ?
I heard about startActivity(app-package,app Activity) but its not working, it says startActivity() not defined for Web Driver .
public class Calculator {
WebDriver driver;
#BeforeClass
public void setUp() throws MalformedURLException{
//Set up desired capabilities and pass the Android app-activity and app-package to Appium
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Android");
capabilities.setCapability(CapabilityType.VERSION, "4.4");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("deviceName", "14085521650378");
capabilities.setCapability("appPackage", "com.android.calculator2"); // This is package name of your app (you can get it from apk info app)
capabilities.setCapability("appActivity","com.android.calculator2.Calculator");
configurations specified in Desired Capabilities
driver = new RemoteWebDriver(new URL("http://127.0.0.1:9515/wd/hub"), capabilities);
}
#Test
public void testCal(){
driver.findElement(By.name("2")).click();
driver.findElement(By.name("+")).click();
driver.findElement(By.name("4")).click();
driver.findElement(By.name("=")).click();
}
#Test
public void Test2() { driver.startActivity("appPackage", "com.tttk.apc","appActivity","com.tttk.apc.DWDemoActivity");
for(int i=0; i<20;i++)
driver.findElement(By.className("android.widget.ImageButton")).click();
}
#AfterClass
public void teardown(){
//close the app
driver.quit();
}}
Seems like you are trying to use the method with a WebDriver instance.
The startActivity method is provided by an interface StartsActivity implemented by AndroidDriver only. So ideally this shall work :
((AndroidDriver) driver).startActivity(<appPackage>, <appActivity>);
public static void start() {
try {
((AndroidDriver) driver).startActivity("com.example.test", "com.example.LaunchApp");
} catch (Exception e) {
e.printStackTrace();
}
}
You have to enter your app package name and activity name to maximize the app.

Categories

Resources