Moq框架测试方法执行次数

时间:2016-05-30 07:25:11

标签: c# unit-testing moq

请查看下面的代码,验证总是失败。有人可以帮忙吗?

public class ViewModel
{
    private IMyDataService dataService = null;

    public ViewModel(IMyDataService dataService)
    {
        this.dataService = dataService;
    }

    public Dictionary<string, string> filters {get; set;}

    public void ProcessFilters()
    {
        dataService.ProcessFilters(filters);
    }
}

[TestMethod]
public void ProcessFilters_Test()
{
    var mockService = new Mock<IMyDataService>();
    ViewModel vm = new ViewModel(mockService.Object);
    Dictionary<string,string> filters = null;
    vm.ProcessFilters(filters);
    mockService.Verify(x=>x.ProcessFilters(filters), Times.Once);
}

2 个答案:

答案 0 :(得分:0)

请注意,属于ProcessFilters类的ViewModel方法不接受任何参数,因此您实际上并未调用该方法。如果您正在尝试测试属于ProcessFilters类的ViewModel方法是否仅使用IMyDataService参数filters调用模拟的null 1}},然后尝试类似:

[TestMethod]
public void ProcessFilters_Test()
{
    // Arrange.
    var mock = new Mock<IMyDataService>();
    var vm = new ViewModel(mock.Object);

    // Act.
    vm.ProcessFilters();

    // Assert.
    mock.Verify(s => s.ProcessFilters(null), Times.Once());
}

答案 1 :(得分:0)

根据verify-a-method-call-using-moq,您必须先设置方法,然后才能对其进行验证:

var mockService = new Mock<IMyDataService>();
mockService.Setup(mock => mock.ProcessFilter(null));
ViewModel vm = new ViewModel(mockService.Object);
Dictionary<string,string> filters = null;

// Act
vm.ProcessFilters(filters);

// Assert
mockService.Verify(x=>x.ProcessFilters(filters), Times.Once);

此外,ProcessFilters中的ViewModel - 方法不期望任何参数。但是,您的类中有filters - 属性未设置(至少不在您提供的代码中)。因此,您必须将相应的参数添加到方法签名或设置属性:

vm.Filters = filters;
vm.ProcessFilters();