Search code examples
xamarin.formsxamarin.androidxamarin.iosui-testing

How do I write UITests for Xamarin Buttons?


I'm trying to write cross-platform tests in Xamarin to check labels on a button. This works for simple <Label /> items in my XAML:

static readonly Func<AppQuery, AppQuery> Welcome = c => c.Marked("Welcome").Text("Welcome!");

but when I try the same thing with a <Button /> :

static readonly Func<AppQuery, AppQuery> NewButton = c => c.Button("NewLine").Text("New Line");

my iOS tests fail but the Android tests pass.

The issue seems to be that the XAML fields get mapped differently depending on whether I'm running iOS or Android.

This is what I see in Android:

Android debug info

And this is what I see in iOS:

iOS debug info

In Android, the AutomationId gets mapped to the Label and the Text maps to Text (the Label field doesn't exist).

In iOS, the AutomationId gets mapped to the Id and the Text gets mapped to the Label (and the Text is null).

Does this just mean I need to write different tests for iOS compared with Android? Or is there a smarter way to do it?


Solution

  • In an attempt to move forward, I just did this... but it feels sub-optimal.

    private void TestButton(string automationId, string text, string errorMessage)
    {
        Func<AppQuery, AppQuery> query = c => c.Button(automationId);
    
        AppResult[] result = app.Query(query);
    
        Assert.IsTrue(result.Length > 0, "No buttons with ID '" + automationId + "' found.");
    
        var textField = result[0]?.Text;
        var labelField = result[0]?.Label;
    
        Assert.IsTrue(textField == text || labelField == text, errorMessage);
    }