使用Moq模拟MVVM交叉导航服务的正确语法



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

正如Moq存储库中的这个问题所解释的,您不能跳过可选参数。

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

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

相关内容

  • 没有找到相关文章

最新更新