【问题标题】:Verifying Moq method call when used as a base class/interface用作基类/接口时验证 Moq 方法调用
【发布时间】:2015-09-18 14:40:03
【问题描述】:

我正在尝试验证实现以下接口的 Moq 上的方法调用,但它与调用不匹配。

我的单元测试(简化):

[Test]
public void ShouldDeleteComponent()
{
    var mockDao = new Mock<IComponentDataAccess>();

    Target.ComponentDao = mockDao.Object;
    Target.Execute();

    mockDao.Verify(x => x.Delete(It.IsAny<Component>()), Times.Once);
}

我的模拟对象的接口:

public interface IComponentDataAccess : IDataAccess<Component>
{
    int Delete(Component entity);
}

public interface IDataAccess<T> where T : IEntity
{
    int Delete(T entity);
}

最后,代码是如何在被测系统中实际调用的:

public override void Execute()
{
    DeleteItem(ComponentDao, existingComponent);
}

调用:

protected virtual void DeleteItem<T>(IDataAccess<T> dataAccess, T item) where T : IEntity
{
    dataAccess.Delete(item);
}

如您所见,DAO 作为其基本接口传入。在验证时,它会找到以下调用:

执行的调用:

IDataAccess`1.Update(blah.namespace.UserAccount)

当它试图匹配的调用是:

IUserAccountDataAccess.Update(blah.namespace.UserAccount)

有没有办法用 Moq 验证这个方法调用?

【问题讨论】:

    标签: c# unit-testing mocking moq assert


    【解决方案1】:

    改变:

    mockDao.Verify(x => x.Delete(It.IsAny<Component>()), Times.Once);
    

    到:

    mockDao.As<IDataAccess<Component>>()
           .Verify(x => x.Delete(It.IsAny<Component>()), Times.Once);
    

    As 方法正在用于添加其他类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 2011-10-02
      相关资源
      最近更新 更多