Mark Wardell
Mark Wardell

Reputation: 555

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

I have a Xamarin Forms Project That targets iOS. I am trying to write Xamarin.UITests that depend on existence of certain files inside the /Documents folder on the device In trying to read/write the files to the correct Folder here is what I found.

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

  1. Results From actual app :

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

  1. Results From Xamarin.UITest :

"/Users/markwardell/”

Clearly I need a way of getting same result as 1..

How can I get the folder results same as app in the UITest?

Upvotes: 0

Views: 322

Answers (1)

jgoldberger - MSFT
jgoldberger - MSFT

Reputation: 6088

The UITest project does not have access to the Xamarin.iOS SDK which is the SDK that is giving you the path from the actual app when deployed to a device or simulator. IOW, the System namespace in Xamarin.iOS's version of .NET/Mono implements some things differently depending on the platform, as is necessary in this case since the documents path is different on iOS than it is on Android, than it is on Windows, etc. So this is why the paths are different.

That said, you can get around this by using a backdoor method. See: https://learn.microsoft.com/en-us/appcenter/test-cloud/uitest/working-with-backdoors

This allows you to call a method implemented in the iOS project itself, thereby using Xamarin.iOS SDK in that method.

You implement the backdoor method in your AppDelegate class in your iOS app project like so:

    [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));
    }

Then call it from your UI Test project:

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

Worth noting from the linked doc (in case it ever goes away):

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.

Upvotes: 1

Related Questions