Search code examples
c#moqxunitfilepicker

How can I Mock async method holding CrossFilePicker?


I am working on Xamarin.Forms project, that is using Autofac, Moq, and Plugin.FilePicker.

One of button commands is calling method:

private async void OnLoadFileExecute(object obj)
{
    await PickUpFile();
    LoadedPhrases = LoadFromFile(FileLocation);
    PopulateDb(LoadedPhrases);
    LoadGroups();
}

And PickUpFile() method is async:

public async Task<string> PickUpFile()
{
    try
    {
        FileLocation = "";
        var file = await CrossFilePicker.Current.PickFile();
        if (file != null)
        {
            FileLocation = file.FilePath;
            return FileLocation;
        }
        else
        {
            FileLocation = "";
            return "";
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine("Exception choosing file: " + ex.ToString());
        return "";
    }
}

I wanted to test whole command, so all methods in OnLoadFileExecute will be tested. In that case I am not sure how can I Setup PickUpFile() method to return some string. As far as I know, I can not use in the interface async methods. Correct me if I am wrong. If I could, I would be able to mock it.


Solution

  • You can use Task in the interface. When you mock it, you will need to return Task.FromResult