模拟问题:无法实例化 class 的代理:Microsoft.AspNetCore.Identity.UserManager`

Mocking issue: Can not instantiate proxy of class: Microsoft.AspNetCore.Identity.UserManager`

我正在尝试使用测试 Microsoft.AspNetCore.Identity 用户管理器的 Moq 创建单元测试。我知道 Moq 很适合模拟接口,但是 UserManager 没有接口。

这是我的代码:

Mock<UserManager<User>> userManagerMock = new Mock<UserManager<User>>();
// rest of my code ...

这里是错误:

Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: Microsoft.AspNetCore.Identity.UserManager`1[[WebAPI.Core.Model.User, Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
Could not find a parameterless constructor.

您可以使用 Moq 模拟 classes。您只需要使用有效的构造函数参数创建一个新的 Mock。 你的情况:

var userManagerMock = new Mock<UserManager<User>>(Mock.Of<IUserStore<User>>(), null, null, null, null, null, null, null, null);

当为 class 创建新模拟时,Moq 使用 class 的构造函数之一,在 UserManager class 中,有一个构造函数有 9参数:

UserManager<TUser>(IUserStore<TUser>, IOptions<IdentityOptions>, IPasswordHasher<TUser>, IEnumerable<IUserValidator<TUser>>, IEnumerable<IPasswordValidator<TUser>>, ILookupNormalizer, IdentityErrorDescriber, IServiceProvider, ILogger<UserManager<TUser>>)

唯一必须的参数是第一个参数,所有其他参数都可以传递 null 值。

现在您可以设置任何虚拟方法或 属性。

完整示例:

[TestMethod]
public void MockUserManager()
{
    // Arrange
    var userManagerMock = new Mock<UserManager<User>>(Mock.Of<IUserStore<User>>(), null, null, null, null, null, null, null, null);
    userManagerMock.Setup(x => x.CheckPasswordAsync(It.IsAny<User>(), It.IsAny<string>())).ReturnsAsync(true);

    // Act
    var res = userManagerMock.Object.CheckPasswordAsync(new User(), "123456").Result;

    // Assert
    Assert.IsTrue(res);
}

public class User
{
}