【问题标题】:How to mock out the UserManager in ASP.NET 5如何在 ASP.NET 5 中模拟 UserManager
【发布时间】:2016-03-26 20:53:28
【问题描述】:

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

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

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

【问题讨论】:

  • 您找到解决方案了吗?我正在尝试为我的帐户控制器创建一个单元测试。
  • 基本上只是决定等待xunit支持。

标签: c# unit-testing asp.net-core asp.net-core-mvc xunit.net


【解决方案1】:

我在 MVC Music Store 示例应用程序的帮助下管理了它。

在我的单元测试类中,我像这样设置数据库上下文和 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!");
    ...
}

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

【讨论】:

  • 感谢您提供指向源代码的链接 - 在我的应用程序中,您的代码使 UserManager.GetUserAsync 返回 null,但在从 MusicStore 示例重建它之后,我得到了它的工作。 :-)
猜你喜欢
  • 2019-08-20
  • 1970-01-01
  • 2023-04-04
  • 2018-08-16
  • 1970-01-01
  • 2014-04-26
  • 2021-09-12
  • 2016-11-09
相关资源
最近更新 更多