Search code examples
c#appiumappium-android

Selecting web element with id in appium test started using AndroidDriver


I'm new to Appium and testing as a whole. I used Android driver to test an app in android.

I can handle all clicks and typing in the app. But the issue arises while using the OAuth service to log in the app.

I use the following Driver client. appium dotnet driver

The login service opens in a separate chrome browser. I have to type text in an input element inside the web page.

I use the following code. On debugging page resource only has the android elements of the chrome browser and nothing of the web content.

var appiumDriver = new AndroidDriver<AndroidElement>(driverUri, appiumOptions);

[Test()]
[Order(1)]
public async Task TestLogin()
{
    try
    {
        appiumDriver.FindElementByAccessibilityId("Login").Click();
        await Task.Delay(3000);
        var source = appiumDriver.PageSource;
        var element = appiumDriver.FindElementById("login-email");
    }
    catch (NoSuchElementException ex)
    {
    }
}

Can anyone suggest how to proceed with this problem? This also has to be done in iOS, I guess both can be handled the same way.. Thanks in advance.


Solution

  • The issue was not changing to web context for searching in web page. The test flow had to be

    1. Perform action to open the web page from the app. (In my case clicking login button)
    2. Wait till the web page appears. (This is important as the web context will be available only after the web page appears) For this, I used a FindElementByClassName for a unique control visible in the web page but not on the previous App page. There sure can be a better way.
    3. Get available contexts and switch to web context.
    4. I used FindByCssSelector for finding the element with id.

    Changing to web context

    public static void ChangeToWebContext()
    {
        if (driver.Context != "NATIVE_APP")
            return;
    
        var elements = driver.FindElementByClassName("android.widget.EditText");
    
        var availableContext = driver.Contexts;
        if (availableContext.Count >= 2)
        {
            driver.Context = availableContext[1];
            return;
        }
    }
    

    Usgae:

    this.ChangeToWebContext();
    driver.FindElementByCssSelector("#login-password");