如何在使用 Xamarin.UITest 时伪造背景 activity

How to fake background activity while using Xamarin.UITest

我正在创建一个 Xamarin.Forms 应用程序并想使用 UITest 来测试我的视图的正确行为。 View 不仅对用户输入做出反应,例如按钮单击等。相反,有一些后台操作会导致视图发生变化,例如此时隐藏一个元素并显示另一个元素。另一个示例是用后台操作生成的元素填充 ListView。这些更改将在其属性绑定到视图的 ViewModel 上进行。 现在我想模拟后台操作并测试我的视图是否正确运行。但是我无法在 UITest 项目中操作我的 ViewModel,因为我无法在测试 class 中引用 Xamarin.Forms。 似乎不打算以这种方式测试应用程序。整个应用程序是 UITest 的黑盒,您只能通过鼠标和键盘输入与其进行交互。 我如何访问我的应用程序的内部结构,例如相应的 ViewModel。 我已经搜索过这个问题,但一无所获。也许我正在寻找错误的方向。 任何帮助将不胜感激。

您可以使用后门访问平台项目中的方法,并且您应该能够从那里访问表单代码,因为您的应用项目引用了表单核心项目。参见:https://developer.xamarin.com/guides/testcloud/uitest/working-with/backdoors/

在Android项目中创建后门方法:

在 MainActivity 中:

[Export("MyBackdoorMethod")]
// Can optionally take a parameter of string, int, or bool.
// Can optionally return  string or Java.Lang.String. 
public void MyBackdoorMethod() 
{
    // In through the backdoor - do some work.
}

要从测试中调用 Android 后门方法:

app.Invoke("MyBackdoorMethod");

在iOS项目中创建后门方法:

在 AppDelegate 中:

[Export("myBackdoorMethod:")] // notice the colon at the end of the method name
// Must take an NSString and return an NSString.
public NSString MyBackdoorMethod(NSString value)
{
    // In through the backdoor - do some work.
}

要从测试中调用 iOS 后门方法:

app.Invoke("myBackdoorMethod:", "the value");

link 中有更多详细信息,但这应该足以启动。

在 iOS 上,您已经有一种方法可以实现它,称为 SendAppToBackground。您还可以使用 TimeSpan 对象 (wiki info) 来传递在后台的时间。但是,您无法在 Android 上实现此目的。

这是一个在您的 UITest 项目中使用它的示例:

public void SendAppToBackground(IApp app, TimeSpan timeSpan)
{
    if (OnAndroid)
    {
        return;
    }

    ((iOSApp)app).SendAppToBackground(timeSpan);

    app.Screenshot("Return from background state.");

    return this;
}