如何在 ASP.NET 5 中模拟 UserManager

How to mock out the UserManager in ASP.NET 5

我正在编写 UI 用于在 ASP.NET 5 应用程序中管理用户。我需要在 UI 中显示 UserManager 返回的任何错误。我在视图模型中传回了 IdentityResult 错误,但在测试我的代码时我有点随波逐流。

ASP.NET 5 中模拟 UserManager 的最佳方法是什么?

我是否应该继承 UserManager 并覆盖我正在使用的所有方法,然后将我的 UserManager 版本注入到我的测试项目中 Controller 的实例中?

我在 MVC 音乐商店示例应用程序的帮助下管理了它。

在我的单元测试 class 中,我像这样设置数据库上下文和 UserManager:

public class DatabaseSetupTests : IDisposable
{
    private MyDbContext Context { get; }

    private UserManager<ApplicationUser> UserManager { get; }

    public DatabaseSetupTests()
    {
        var services = new ServiceCollection();
        services.AddEntityFramework()
            .AddInMemoryDatabase()
            .AddDbContext<MyDbContext>(options => options.UseInMemoryDatabase());
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<MyDbContext>();
        // Taken from https://github.com/aspnet/MusicStore/blob/dev/test/MusicStore.Test/ManageControllerTest.cs (and modified)
        // IHttpContextAccessor is required for SignInManager, and UserManager
        var context = new DefaultHttpContext();
        context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
        services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });
        var serviceProvider = services.BuildServiceProvider();
        Context = serviceProvider.GetRequiredService<MyDbContext>();
        UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
    }
....
}

然后我可以在单元测试中使用 UserManager,例如:

[Fact]
public async Task DontCreateAdminUserWhenOtherAdminsPresent()
{
    await UserManager.CreateAsync(new ApplicationUser { UserName = "some@user.com" }, "IDoComplyWithTheRules2016!");
    ...
}

如果您的依赖注入器无法解析 IHttpContextAccessor,那么您将无法创建 UserManager 实例,因为它依赖于它。 我认为(这只是一个假设),对于 Asp.Net 5,UserManager 确实会在您为用户更改基于 cookie 的声明(声​​明、角色...)时负责刷新它们,因此需要一些 HttpContext用于登录/注销操作和 cookie 访问。