自动化 Xamarin ToolbarItem 单击

Automating Xamarin ToolbarItem click

我正在使用 Xamarin.UITest 编写一些自动化程序。 目标应用程序在其标记中包含此内容:

<ContentPage.ToolbarItems>
    <ToolbarItem Icon="Settings" AutomationId="SettingsToolbarItem" Order="Primary" Priority="1" Command="{Binding ShowSettingsCommand}" />
</ContentPage.ToolbarItems>

到目前为止我有 3 种方法:

使用 .Class 和索引成功找到元素

systemMenuButton = x => x.Class("android.support.v7.view.menu.ActionMenuItemView").Index(1);

使用 .属性 找不到元素

systemMenuButton = e => e.Property("Command", "ShowSettingsCommand");

同理,使用.Marked也找不到元素

systemMenuButton = x => x.Marked("SettingsToolbarItem");

相关自动化代码如下:

using Query = System.Func<Xamarin.UITest.Queries.AppQuery, Xamarin.UITest.Queries.AppQuery>;
....
protected readonly Query systemMenuButton = x => x.Marked("SettingsToolbarItem");
....
app.Tap(systemMenuButton);

我得到一个通用的 "unable to find element" 异常:

Unable to find element. Query for Marked("SettingsToolbarItem") gave no results.

在同一 View/Page

上单击 ContentPage.ToolbarItems 块外的其他元素时,我没有收到此异常

我遇到了同样的问题 - 由于某种原因 Android 无法检测到 ToolbarItem.AutomationId

解决方法是为 ToolbarItem.Text 分配与 ToolbarItem.AutomationId 相同的值。

Xamarin.Forms.ContentPage

<ContentPage.ToolbarItems>
    <ToolbarItem Icon="Settings" Text="SettingsToolbarItem" AutomationId="SettingsToolbarItem" Order="Primary" Priority="1" Command="{Binding ShowSettingsCommand}" />
</ContentPage.ToolbarItems>

Xamarin.UITest

using Query = System.Func<Xamarin.UITest.Queries.AppQuery, Xamarin.UITest.Queries.AppQuery>;
// ....
protected readonly Query systemMenuButton = x => x.Marked("SettingsToolbarItem");
//....

public void TapSystemMenuButton()
{
    app.Tap(systemMenuButton);

    app.Screenshot("Tapped System Menu Button");
}

这是一个示例应用程序,我在其中使用类似的逻辑在 UITest 中点击 ToolbarItem:https://github.com/brminnick/InvestmentDataSampleApp/

编辑

在评论中,您提到您无权访问 Xamarin.Forms 应用程序的源代码。

如果您无法更改 Xamarin.Forms 源代码,则必须使用 x => x.Class("ActionMenuItemView").Index(1)

我不建议走这条路,因为 Index 的 int 参数会因设备而异;不保证总是 1.

public void TapSystemMenuButton()
{
    if (app is iOSApp)
        app.Tap(systemMenuButton);
    else
        app.Tap(x => x.Class("ActionMenuItemView").Index(1));

    app.Screenshot("Tapped System Menu Button");
}