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

时间:2018-11-09 08:15:10

标签: c# xamarin moq mvvmcross

我对MVVMCross和Moq相当陌生,我需要一些模拟MvxNavigation Service格式的帮助。我的代码中有一个我想模拟的电话。

我本以为可以通过执行以下操作来设置返回值:

 _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>()));
    }

}

1 个答案:

答案 0 :(得分:1)

如Moq存储库中的this issue所述,您不能仅跳过可选参数。

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

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