【问题标题】:How to get access to method in base interface with Moq?如何使用 Moq 访问基本接口中的方法?
【发布时间】:2015-05-10 15:32:09
【问题描述】:

我有如下界面:

public interface IUserRepository : IRepositoryBase
{
    void AddUser(User user);
}

IRepositoryBase 有一个方法Update(params object[] entities)

现在我想在 Moq 中检查此方法的内容。我尝试的是这样的:

// ARRANGE
var userRepositoryMock = new Mock<IUserRepository>();
(...)

// ASSERT
userRepositoryMock.Verify(mock =>
    mock.Update(It.Is<User>(
        u => u.CreationDate.Date == DateTime.Today
          && u.Email == expectedEmail
          && u.FullName == expectedFullName
          && u.Name == expectedUserName)),
       Times.Once,
       "The existing user should be updated with the correct information.");

不幸的是,由于 Update 方法是 IUserRepository 继承自的接口的一部分,因此我无法访问它。可以在错误消息中看到它是基类的一部分:

Moq.MockException
预期在模拟上调用一次,但为 0 次 (...)

执行的调用:
IUserRepository.AddUser(用户)
IRepositoryBase.Update(System.Object[])
IRepositoryBase.SaveChanges()

有人知道如何检查基接口的方法调用吗?

【问题讨论】:

    标签: c# unit-testing moq


    【解决方案1】:

    IUserRepository 有效地吸收了基础存储库的成员,所以这不是问题。

    您的 Update 方法采用一个对象数组,因此您需要对此进行验证。我们可以在执行的调用中看到您的方法确实是使用对象数组调用的。您的验证仅针对单个用户设置(编译器允许使用 params 关键字)。

    params 关键字实际上只是一个编译器技巧,可以更轻松地传递 0 个或多个参数。将在底层创建一个包含所有参数的数组。

    【讨论】:

    • 谢谢你是对的。 :-) 我将其修复如下:userRepositoryMock.Verify(mock =&gt; mock.Update(It.Is&lt;Object[]&gt;(u =&gt; ((User)u[0]).AuthenticationStatus == AuthenticatedStatus.Authenticated &amp;&amp; ((User)u[0]).CreationDate.Date == DateTime.Today &amp;&amp; ((User)u[0]).Email == expectedEmail &amp;&amp; ((User)u[0]).FullName == expectedFullName &amp;&amp; ((User)u[0]).Name == expectedUserName)), Times.Once, "The existing user should be updated with the correct information.")
    • 酷,不用担心。我还建议使您的基本存储库通用,而不是让它接受对象。它会让事情的类型更安全,并且让你不必在你的代码中进行强制转换。
    • 谢谢克里斯。您知道如何制作通用存储库的好解释吗?
    • 这可能是个不错的起点:remondo.net/repository-pattern-example-csharp
    • 谢谢,我去看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 2012-05-17
    • 2015-10-03
    • 2023-03-22
    • 2017-10-23
    相关资源
    最近更新 更多