2017-12-18 352 views
1

我正在使用導航服務來執行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. 
}  

回答

0

我發現如何模擬和測試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