我如何模拟保持CrossFilePicker的异步方法?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (30)

我的工作Xamarin.Forms项目,正在使用AutofacMoqPlugin.FilePicker

其中一个按钮命令是调用方法:

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

PickUpFile()方法是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 "";
    }
}

我想测试整个命令,所以OnLoadFileExecute将测试所有方法。在那种情况下,我不知道如何设置PickUpFile()方法返回一些string。据我所知,我不能在interface异步方法中使用。如果我错了,请纠正我。如果可以的话,我可以嘲笑它。

提问于
用户回答回答于

您可以将Task在界面中使用。当你嘲笑它时,你需要返回Task.FromResult

用户回答回答于

在我看来,应该是这样

public interface IFileService {
    Task<string> PickUpFile();
}

public class FileService : IFileService {
    public async Task<string> PickUpFile() {
        // here you have your implementation
    }
}

// Here is the test method
public async Task TestTheService() {
    const string fileName = "filename.txt";

    var fileMocker = new Mock<IFileService>();
    fileMocker.Setup( x => x.PickUpFile() ).Returns( Task.FromResult( fileName ) );
    var mainClass = new MainClass( fileMocker.Object );
    await mainClass.OnLoadFileExecute( null );
    Assert.Equal( fileName, mainClass.FileLocation );
}

// here is the real class

public class MainClass {
    private IFileService FileService { get; }
    public string FileLocation { get; set; }

    public MainClass( IFileService fileService ) {
        FileService = fileService;
    }

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

扫码关注云+社区

领取腾讯云代金券