为什么我的异步命令调用单元测试不起作用?

时间:2019-07-08 13:47:24

标签: c# command task moq xunit

好吧,我已经尝试算了几个小时,所以我决定在这里提问。

我正在使用 xUnit Moq 框架。

关于我的SUT的几句话。我有一个异步命令:

public IAsyncCommand SimulateResultsCommand { get; private set; }

该命令调用一个方法:

SimulateResultsCommand = new AsyncCommand(async () => await OnSimulateResultsExecuteAsync());

方法正在调用服务层方法:

public async Task OnSimulateResultsExecuteAsync()
{
    //init controls here

    Races = await _simulateDataService.SimulateResultsAsync(It.IsAny<int>(), Races.Count, Races, Horses, Jockeys, RaceModelProvider);

    //reset controls here
}

有关创建异步命令的信息,请参见this answer。问题是,当我测试它时,测试失败并显示一条消息:

  

消息:Moq.MockException:预期一次模拟调用,   但是是0次:sd => sd.SimulateResultsAsync(It.IsAny(),0,[],[],[],   RaceModel)

     

执行的调用:

     

模拟(sd):

     

ISimulateService.SimulateResultsAsync(0,0,[],[],[],RaceModel)

测试看起来像这样:

[Fact]
public async Task OnSimulateResultsExecuteAsync_CallsSimulateResultsAsync()
{
    List<RaceDetails> races = new List<RaceDetails>();
    List<LoadedHorse> horses = new List<LoadedHorse>();
    List<LoadedJockey> jockeys = new List<LoadedJockey>();
    RaceModel race = new RaceModel();

    await _viewModel.SimulateResultsCommand.ExecuteAsync(null);

    _simulateDataMock.Verify(sd => sd.SimulateResultsAsync(0, races.Count, races, horses, jockeys, race), Times.Once);
}

模拟注射:

private MainViewModel _viewModel;
private Mock<ISimulateService> _simulateDataMock;

public MainViewModelTests()
{
    _simulateDataMock = new Mock<ISimulateService>();

    _viewModel = new MainViewModel(_simulateDataMock.Object);
}

我在做什么错?为什么模拟中没有调用

1 个答案:

答案 0 :(得分:3)

您应使用It.IsAny<T>()将参数匹配 any 值:

_simulateDataMock.Verify(sd => sd.SimulateResultsAsync(It.IsAny<int>(), It.IsAny<int>(),
    It.IsAny<List<RaceDetails>>(), It.IsAny<List<LoadedHorse>>(), It.IsAny<List<LoadedJockey>>(),
    It.IsAny<RaceModel>()), Times.Once);