如何在.Net Core测试中模拟UserManager?

时间:2018-03-08 05:08:01

标签: c# unit-testing asp.net-core mocking asp.net-core-identity

我有以下代码。我试图为创建用户运行一个测试用例。以下是我到目前为止所尝试的。

public class CreateUserCommandHandlerTest
{
    private Mock<UserManager<ApplicationUser>> _userManager;
    private CreateUserCommandHandler _systemUnderTest;

    public CreateUserCommandHandlerTest()
    {
        _userManager = MockUserManager.GetUserManager<ApplicationUser>();
        var user = new ApplicationUser() { UserName = "ancon1", Email = "ancon@mail.com", RoleType = RoleTypes.Anonymous };
        _userManager
            .Setup(u => u.CreateAsync(user, "ancon2")).ReturnsAsync(IdentityResult.Success);
        _systemUnderTest = new CreateUserCommandHandler(_userManager.Object);
    }

    [Fact]
    public async void Handle_GivenValidInput_ReturnsCreatedResponse()
    {
        var command = new CreateUserCommand { Username = "ancon1", Email = "ancon@mail.com", Password = "ancon2", RoleType = RoleTypes.Anonymous };
        var result = await _systemUnderTest.Handle(command, default(CancellationToken));
        Assert.NotNull(result);
        Assert.IsType<Application.Commands.CreatedResponse>(result);
    }
}

我的用户经理在这里:

public static class MockUserManager
{
    public static Mock<UserManager<TUser>> GetUserManager<TUser>()
        where TUser : class
    {
        var store = new Mock<IUserStore<TUser>>();
        var passwordHasher = new Mock<IPasswordHasher<TUser>>();
        IList<IUserValidator<TUser>> userValidators = new List<IUserValidator<TUser>>
        {
            new UserValidator<TUser>()
        };
        IList<IPasswordValidator<TUser>> passwordValidators = new List<IPasswordValidator<TUser>>
        {
            new PasswordValidator<TUser>()
        };
        userValidators.Add(new UserValidator<TUser>());
        passwordValidators.Add(new PasswordValidator<TUser>());
        var userManager = new Mock<UserManager<TUser>>(store.Object, null, passwordHasher.Object, userValidators, passwordValidators, null, null, null, null);
        return userManager;
    }
}

我的命令处理程序是这样的:

 public class CreateUserCommandHandler : IRequestHandler<CreateUserCommand, BaseCommandResponse>
{
    private readonly UserManager<ApplicationUser> _userManager;

    public CreateUserCommandHandler(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<BaseCommandResponse> Handle(CreateUserCommand createUserCommand, CancellationToken cancellationToken)
    {
        var user = new ApplicationUser { UserName = createUserCommand.Username, Email = createUserCommand.Email, RoleType = createUserCommand.RoleType };
        var result = await _userManager.CreateAsync(user, createUserCommand.Password);
        if (result.Succeeded)
        {
            return new CreatedResponse();
        }

        ErrorResponse errorResponse = new ErrorResponse(result.Errors.Select(e => e.Description).First());

        return errorResponse;
    }
}

当我正在运行我的测试时,它失败并且说对象引用没有设置为对象的瞬间。

我在这里做错了什么?

3 个答案:

答案 0 :(得分:10)

aspnet/Identity是开源的,所以你能做的就是看看他们是如何自己模仿的。

以下是他们的表现:MockHelpers.cs

TestUserManager

public static UserManager<TUser> TestUserManager<TUser>(IUserStore<TUser> store = null) where TUser : class
{
    store = store ?? new Mock<IUserStore<TUser>>().Object;
    var options = new Mock<IOptions<IdentityOptions>>();
    var idOptions = new IdentityOptions();
    idOptions.Lockout.AllowedForNewUsers = false;
    options.Setup(o => o.Value).Returns(idOptions);
    var userValidators = new List<IUserValidator<TUser>>();
    var validator = new Mock<IUserValidator<TUser>>();
    userValidators.Add(validator.Object);
    var pwdValidators = new List<PasswordValidator<TUser>>();
    pwdValidators.Add(new PasswordValidator<TUser>());
    var userManager = new UserManager<TUser>(store, options.Object, new PasswordHasher<TUser>(),
        userValidators, pwdValidators, new UpperInvariantLookupNormalizer(),
        new IdentityErrorDescriber(), null,
        new Mock<ILogger<UserManager<TUser>>>().Object);
    validator.Setup(v => v.ValidateAsync(userManager, It.IsAny<TUser>()))
        .Returns(Task.FromResult(IdentityResult.Success)).Verifiable();
    return userManager;
}

答案 1 :(得分:3)

我知道这已经几个月了,但是我一直回到这个话题。我将针对这个主题扩展自己的答案,因为仅指向Haok的GitHub示例就好比说:“读一本书”,因为它很大。它没有指出问题和您需要做什么。您需要隔离一个Mock对象,但不仅如此,还需要“设置”“ CreateAsync”的方法。因此,我们将其分为三个部分:

  1. 如果您使用MOQ或类似框架来模拟UserManager,则需要进行MOCK。
  2. 您需要设置希望从中获取结果的UserManager的方法。
  3. (可选)您可能希望从模拟的Entity Framework Core 2.1或类似物中注入一些通用列表,以便实际上可以看到IDentity用户列表实际上在增加还是减少。不仅UserManager成功了,而且没有其他

所以说我有一个用于返回模拟的UserManager的辅助方法。与Haok代码稍有不同:

public static Mock<UserManager<TUser>> MockUserManager<TUser>(List<TUser> ls) where TUser : class
{
    var store = new Mock<IUserStore<TUser>>();
    var mgr = new Mock<UserManager<TUser>>(store.Object, null, null, null, null, null, null, null, null);
    mgr.Object.UserValidators.Add(new UserValidator<TUser>());
    mgr.Object.PasswordValidators.Add(new PasswordValidator<TUser>());

    mgr.Setup(x => x.DeleteAsync(It.IsAny<TUser>())).ReturnsAsync(IdentityResult.Success);
    mgr.Setup(x => x.CreateAsync(It.IsAny<TUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success).Callback<TUser, string>((x, y) => ls.Add(x));
    mgr.Setup(x => x.UpdateAsync(It.IsAny<TUser>())).ReturnsAsync(IdentityResult.Success);

    return mgr;
}

关键是要注入一个通用的“ TUser”,这也是我将要测试的,并注入了一个列表。类似于我的示例:

 private List<ApplicationUser> _users = new List<ApplicationUser>
 {
      new ApplicationUser("User1", "user1@bv.com") { Id = 1 },
      new ApplicationUser("User2", "user2@bv.com") { Id = 2 }
 };

 ...
 var userManager = IdentityMocking.MockUserManager<ApplicationUser>(_users); 

然后,最后我要使用与我要测试的实现类似的存储库来测试模式:

 public async Task<int> CreateUser(ApplicationUser user, string password) => (await _userManager.CreateAsync(user, password)).Succeeded ? user.Id : -1;

我这样测试:

 [Fact]
 public async Task CreateAUser()
 {
      var newUser = new ApplicationUser("NewUser", "New@test.com");
      var password = "P@ssw0rd!";

      var result = await _repo.CreateUser(newUser, password);

      Assert.Equal(3, _users.Count);
  }

我所做的关键是不仅我“设置”了CreateAsync,而且还提供了一个回调,这样我才能真正看到我注入的列表得到增加。希望这对某人有帮助。

答案 2 :(得分:0)

在.NetCore 2.2中,您必须做一些稍有不同。像对待@Nick Chapsas答案的更新一样对待它。

首先,您必须使用IUserPasswordStore而不是IUserStore。 IUserPasswordStore继承了IUserStore,但是UserManager想要获取IUserPasswordStore。否则,某些事情将无法正常工作。

如果要测试UserManager的实际行为(例如CreateUserAsync),则可以使用UserValidator和PasswordValidator的实际实现。您可能只想确保您的方法能对CreateUser错误做出应有的反应。

这是我更新的示例:

UserManager<TUser> CreateUserManager() where TUser : class
{
    Mock<IUserPasswordStore<TUser>> userPasswordStore = new Mock<IUserPasswordStore<TUser>>();
    userPasswordStore.Setup(s => s.CreateAsync(It.IsAny<TUser>(), It.IsAny<CancellationToken>()))
        .Returns(Task.FromResult(IdentityResult.Success));

    var options = new Mock<IOptions<IdentityOptions>>();
    var idOptions = new IdentityOptions();

    //this should be keep in sync with settings in ConfigureIdentity in WebApi -> Startup.cs
    idOptions.Lockout.AllowedForNewUsers = false;
    idOptions.Password.RequireDigit = true;
    idOptions.Password.RequireLowercase = true;
    idOptions.Password.RequireNonAlphanumeric = true;
    idOptions.Password.RequireUppercase = true;
    idOptions.Password.RequiredLength = 8;
    idOptions.Password.RequiredUniqueChars = 1;

    idOptions.SignIn.RequireConfirmedEmail = false;

    // Lockout settings.
    idOptions.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    idOptions.Lockout.MaxFailedAccessAttempts = 5;
    idOptions.Lockout.AllowedForNewUsers = true;


    options.Setup(o => o.Value).Returns(idOptions);
    var userValidators = new List<IUserValidator<TUser>>();
    UserValidator<TUser> validator = new UserValidator<TUser>();
    userValidators.Add(validator);

    var passValidator = new PasswordValidator<TUser>();
    var pwdValidators = new List<IPasswordValidator<TUser>>();
    pwdValidators.Add(passValidator);
    var userManager = new UserManager<TUser>(userPasswordStore.Object, options.Object, new PasswordHasher<TUser>(),
        userValidators, pwdValidators, new UpperInvariantLookupNormalizer(),
        new IdentityErrorDescriber(), null,
        new Mock<ILogger<UserManager<TUser>>>().Object);

    return userManager;
}

请注意,如果您要从UserManager测试CreateAsync,则UserPasswordStore的方法(CreateAsync)应该被模拟。

密码和锁定设置来自我的项目。它们应该与您的设置保持同步,以便您可以测试真实的东西。

当然您不会测试例如PasswordValidator,但是您可以测试您的方法,例如:

//Part of user service
public async Task<IdentityResult> Register(UserDto data)
{
    SystemUser user = ConvertDtoToUser(data);
    IdentityResult result = userManager.CreateAsync(user, data.Password);

    //some more code that is dependent on the result
}