Search code examples
c#automationappium

Cannot find element before timeout ends


I'm creating simple test automation project using appium, C#. its opening app correctly and after that code cannot click on the element. and show exception "OpenQA.Selenium.WebDriverException: 'The HTTP request to the remote WebDriver server for URL http://127.0.0.1:4723/wd/hub/session/34e0ca2f-af1f-48ef-aafe-d6a46516a862/element timed out after 60 seconds.'"

Image of the exception

i have tried changing the xpath and driver types

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium.Interfaces;
using System.Threading;
using System.IO;

namespace FlowLogic_Test_Project
{
    [TestClass]
    public class UnitTest1
    {
        AppiumDriver<IWebElement> driver;

        [TestMethod]
        public void TestMethod1()
        {
            DesiredCapabilities capabilities = new DesiredCapabilities();
            capabilities.SetCapability("deviceName", "emulator-5554");
            capabilities.SetCapability("appActivity", ".MainActivity");
            capabilities.SetCapability("appPackage", "com.flowlogicclient");
            capabilities.SetCapability("automationName", "UiAutomator1");

            //Launch the Android driver
            driver = new AndroidDriver<IWebElement>(new Uri("http://127.0.0.1:4723/wd/hub"), capabilities);

            Thread.Sleep(10000);
            driver.FindElementByXPath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.view.ViewGroup/android.view.ViewGroup[2]/android.view.ViewGroup/android.view.ViewGroup[2]/android.view.ViewGroup").Click();
        }
    }
}

Solution

  • Are you sure about this UiAutomator1 capability? If your emulator is running Android 5.1 API level 22 or higher you must use UIAutomator2 otherwise you will not be able to proceed further than application launch.

    You could also reconsider the locator strategy as the preferred way of locating elements on Android is using resource-id. Or at least you could use relative XPath, not starting from <hierarchy> tag but rather uniquely identifying your element using its tag value or text.

    Going forward avoid using Thread.sleep as it's some form of performance anti-pattern, there is WebDriverWait class along with DotNetSeleniumExtras.WaitHelpers providing APIs to wait for elements presence/visibility/clickability/absence/etc. Check out How to use Selenium to test web applications using AJAX technology article to get familiarized with the concept