使用 Moq 模拟 MVVMCross 导航服务的正确语法

Correct syntax for mocking MVVMCross navigation service using Moq

我对 MVVMCross 和 Moq 很陌生,我需要一些关于模拟 MvxNavigation 服务格式的帮助。我的代码中有一个我想模拟的调用。

我原以为我可以通过以下方式设置 return 值:

 _naviageService.Setup(n => n.Navigate<PlaceSelectViewModel, Place, Place>(It.IsAny<Place>())).Returns(returnPlace);

但这不编译。我尝试查看 Moq 快速入门和 MVVMCross 示例,但似乎找不到我想要的东西。请根据要求在下面找到完整的示例:Tnx

public class FooClass
{
    IMvxNavigationService _navigationService;

    public IMvxAsyncCommand SelectPlaceCommand { get; }

    public FooClass(IMvxNavigationService navigationService)
    {
        _navigationService = navigationService;
        SelectedplaceCommand = new MvxAsyncCommand(SelectPlace);
    }

    async Task SelectPlace()
    {

        var place = await _navigationService.Navigate<PlaceSelectViewModel, Place, Place>(new Place());

        // Do somehting with place
    }

}

[TestFixture]
public class FooTests : MvxIoCSupportingTest
{
    Mock<IMvxNavigationService> _navigationService;
    FooClass _foo;

    [SetUp]
    public void SetUp()
    {
        base.Setup();

        _navigationService = new Mock<IMvxNavigationService>();
        _foo = new FooClass(_navigationService.Object);
    }

    [Test]
    public async Task DoSomthing_NavigatesToPlaceSelectViewModel()
    {
        //Arrange


        var returnPlace = new Place { MapTitle = "New Place" };

        await _navigationService.Setup(n => n.Navigate<PlaceSelectViewModel, Place>(It.IsAny<Place>())).Returns(returnPlace);  // ** This is incorrect syntax and does not complile

        //Act
        await _foo.SelectPlaceCommand.ExecuteAsync();

        //Assert
        _navigationService.Verify(s => s.Navigate<PlaceSelectViewModel, Place, Place>
                                  (It.IsAny<Place>(),
                                  null,
                                   It.IsAny<CancellationToken>()));
    }

}

正如 Moq 存储库中的 this issue 所解释的那样,您不能只跳过可选参数。

如果您没有在 Navigate 调用中使用所有参数(或者更准确地说,如果您不关心它们),这是一种解决方法:

_naviageService.Setup(n => n.Navigate<PlaceSelectViewModel, Place, Place>(
        It.IsAny<Place>(), 
        It.IsAny<IMvxBundle>(), 
        It.IsAny<CancellationToken>())
    ).Returns(returnPlace);