Environment.System.Environment.SpecialFolder.MyDocuments Xamarin.UITest 与应用程序不同

Environment.System.Environment.SpecialFolder.MyDocuments Different in Xamarin.UITest than in app

我有一个针对 iOS 的 Xamarin Forms 项目。我正在尝试编写 Xamarin.UITests 这取决于设备上 /Documents 文件夹中某些文件的存在 在尝试 read/write 文件到正确的文件夹时,我发现了这里。

string documentBasePath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);

  1. 来自实际应用的结果:

"/Users/markwardell/Library/Developer/CoreSimulator/Devices/147FD387-FCAD-4E93-BFC7-4BC1572FF7D4/data/Containers/Data/Application/13E0B91B-8C70-4139-B570-7431DDF5B5CA/Documents"

  1. 来自 Xamarin.UITest 的结果:

/Users/markwardell/”

显然我需要一种方法来获得与 1..

相同的结果

如何在 UITest 中获取与 app 相同的文件夹结果?

UI测试项目无法访问 Xamarin.iOS SDK,该 SDK 在部署到设备或模拟器时为您提供实际应用程序的路径。 IOW,Xamarin.iOS 的 .NET/Mono 版本中的系统名称空间根据平台实现了一些不同的东西,在这种情况下是必要的,因为 iOS 上的文档路径与它不同在 Android 上,而不是在 Windows 上,等等。所以这就是路径不同的原因。

也就是说,您可以使用后门方法来绕过这个问题。看: https://docs.microsoft.com/en-us/appcenter/test-cloud/uitest/working-with-backdoors

这允许您调用在 iOS 项目本身中实现的方法,从而在该方法中使用 Xamarin.iOS SDK。

您在 iOS 应用程序项目的 AppDelegate class 中实现后门方法,如下所示:

    [Export("getMyDocumentsPath:")] // notice the colon at the end of the method name
    public NSString GetMyDocumentsPath(NSString value)
    {
        // In through the backdoor - do some work.
        return new NSString(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments));
    }

然后从您的 UI 测试项目中调用它:

var path = app.Invoke("getMyDocumentsPath:", "").ToString();

链接文档中值得注意的地方(以防它消失):

On iOS, IApp.Invoke can call a C# method on the project's AppDelegate according to the following rules:

  • The method must be public.
  • The method must be adorned with the ExportAttribute and the name of the exposed C# method identified. The exposed name must append a : (colon) to the name. IApp.Invoke must use the iOS form of the method name.
  • The method must take a parameter of NSString.
  • The method must return NSString or void.