如何使用 Moq 访问基本接口中的方法?
How to get access to method in base interface with Moq?
我有以下界面:
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 继承自的接口的一部分,因此我无法访问它。它是基础 class 的一部分,可以在错误消息中看到:
Moq.MockException
Expected invocation on the mock once, but was 0 times (...)
Performed invocations:
IUserRepository.AddUser(User)
IRepositoryBase.Update(System.Object[])
IRepositoryBase.SaveChanges()
有谁知道如何检查基接口的方法调用?
IUserRepository 有效地吸收了基本存储库的成员,所以这不是问题。
您的 Update 方法接受一个对象数组,因此这是您需要验证的内容。我们可以在执行的调用中看到您的方法确实是用对象数组调用的。您的验证仅针对单个用户设置(由于 params 关键字,编译器允许这样做)。
params 关键字实际上只是一个编译器技巧,可以更轻松地传入 0 个或更多参数。将在后台创建一个包含所有参数的数组。
我有以下界面:
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 继承自的接口的一部分,因此我无法访问它。它是基础 class 的一部分,可以在错误消息中看到:
Moq.MockException
Expected invocation on the mock once, but was 0 times (...)
Performed invocations:
IUserRepository.AddUser(User)
IRepositoryBase.Update(System.Object[])
IRepositoryBase.SaveChanges()
有谁知道如何检查基接口的方法调用?
IUserRepository 有效地吸收了基本存储库的成员,所以这不是问题。
您的 Update 方法接受一个对象数组,因此这是您需要验证的内容。我们可以在执行的调用中看到您的方法确实是用对象数组调用的。您的验证仅针对单个用户设置(由于 params 关键字,编译器允许这样做)。
params 关键字实际上只是一个编译器技巧,可以更轻松地传入 0 个或更多参数。将在后台创建一个包含所有参数的数组。