我正在使用Xamarin.Forms项目,该项目正在使用Autofac
,Moq
和Plugin.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
异步方法中使用。如果我错了,请纠正我。如果可以的话,我将可以对其进行模拟。
答案 0 :(得分:0)
您可以在界面中使用Task
。模拟时,您需要返回Task.FromResult
答案 1 :(得分:0)
从我的角度来看,它应该像这样
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();
}
}