如何模拟ASP.NET 5中的UserManager

hal*_*y9k 10 c# unit-testing xunit.net asp.net-core-mvc asp.net-core

我正在编写一个用于在ASP.NET 5应用程序中管理用户的UI .我需要在UI中显示UserManager返回的任何错误.我IdentityResult在视图模型中传递了错误,但在测试我的代码时我是一个漂亮的触摸器.

什么是嘲笑的最佳方法UserManagerASP.NET 5

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

Geo*_*ngl 19

我已经在MVC音乐商店示例应用程序的帮助下进行了管理.

在我的Unit Test类中,我设置了数据库上下文和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>>();
    }
....
}
Run Code Online (Sandbox Code Playgroud)

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

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

如果您的Dependency Injector无法解析IHttpContextAccessor,那么您将无法创建UserManager实例,因为它依赖于它.我认为(这只是一个假设),使用Asp.Net 5,当你为用户更改它们(声明,角色......)时,UserManager会处理基于cookie的声明,因此需要一些HttpContext才能登录/ logout操作和cookie访问.