模拟和测试MvvmCross NavigationService

模拟和测试MvvmCross NavigationService

问题描述:

我正在使用导航服务来执行ViewModels之间的导航,现在我必须为ViewModel创建一些单元测试。我能够模拟ViewModel创建Moq注入的对象,但我很努力地模拟NavigationService,然后创建断言,而不是导航到下一个ViewModel。模拟和测试MvvmCross NavigationService

我从几年前发现了一些文档,所以导航服务并不存在,我在官方MvvmCross文档中找不到关于此事的任何内容,所以现在我处于死路一条。

我正在使用MvvmCross 5.5.0。

[Test] 
public void CheckStatus() 
{ 
    Mock<IStatusService> _mockStatusService = new Mock<IStatusService>(); 
    _mockStatusService.Setup(x => x.Check(It.IsAny<StatusRequest>())).Returns(() => new StatusRequest { Ok = true }); 

    //Here I need to pass the NavigationService to the constructor 
    var _viewModel = new StatusViewModel(_mockStatusService.Object, navigationService); 
    _viewModel.Start(); 

    //Here I guess I should perform the navigation assertion. 
}  

我发现如何模拟和测试NavigationService。我在这里发布解决方案,因为这对其他人很有用。

[Test] 
public void CheckStatus() 
{ 
    IFixture _fixture = new Fixture().Customize(new AutoMoqCustomization()); 
    Mock<IMvxNavigationService> _navigationService = _fixture.Freeze<Mock<IMvxNavigationService>>(); 

    var _viewModel = new StatusViewModel(navigationService); 
    _viewModel.Start(); 

    _navigationService.Verify(x => x.Navigate<NextViewModel>(null), Times.Once()); 
}  
+1

您可以使用ViewModelLoader不手动调用启动或其他方法。 – Martijn00