繁体   English   中英

在UseInMemoryDatabase()创建的IdentityDbContext中使用Identity的管理器

[英]Using Identity's Managers in IdentityDbContext that was created by UseInMemoryDatabase()

我制作了这种方法,使单元测试DbContext更加容易。 这种方法使我的db Context在内存中。 之所以有效,是因为我使用实体(例如_context.Projects_context.Tests等,在单元测试中测试此方法)进行了测试:

        public static TaskManagerDbContext Create()
        {
            var options = new DbContextOptionsBuilder<TaskManagerDbContext>()
                                .UseInMemoryDatabase(Guid.NewGuid().ToString())
                                .EnableSensitiveDataLogging(true)
                                .Options;

            var context = new TaskManagerDbContext(options);
            context.SaveChanges();

            return context;
        }

我的DbContextClass看起来像这样:


    public class TaskManagerDbContext : IdentityDbContext<ApplicationUser>, ITaskManagerDbContext
    {
        public TaskManagerDbContext(DbContextOptions<TaskManagerDbContext> options)
            : base(options)
        {
        }

        //db sets here

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfigurationsFromAssembly(typeof(TaskManagerDbContext).Assembly);
        }
    }

我的问题是,我们可以认同的UserManagerSignInManagerRoleManager的记忆,就像我们可以做IdentityDbContext 如何对Identity用户(例如用户),内存中的角色(例如我们可以使用标准Context进行的操作)进行单元测试? 我在测试时如何在存储在内存中的虚假上下文中调用此Managers

编辑:

基于此,问题身份共享具有明显的context 但是如何通过UseInMemoryDatabase()方法在创建的IdentityDbContext上使用Managers

EDIT2:

通过夹具注入context

public class DatabaseFixture
{
    public TaskManagerDbContext Context { get; private set; }

    public DatabaseFixture()
    {
        this.Context = DatabaseContextFactory.Create();
    }
}

[CollectionDefinition("DatabaseTestCollection")]
public class QueryCollection : ICollectionFixture<DatabaseFixture>
{
}

及其用法:

[Collection("DatabaseTestCollection")]
public class RegisterUserCommandTests
{
    private readonly TaskManagerDbContext _context;

    public RegisterUserCommandTests(DatabaseFixture fixture)
    {
        _context = fixture.Create();
    }

    //and usage of it in class:
    var user = _context.Projects.Find(8);
}

我正在使用Xunit

您需要创建一个服务集合,向其中注册所有内容,然后使用它来提取您需要的内容。

var services = new ServiceCollection();
services.AddDbContext<TaskManagerDbContext>(o =>
    o.UseInMemoryDatabase(Guid.NewGuid()));
services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<TaskManagerDbContext>();
var provider = services.BuildServiceProvider();

然后,您可以使用provider

using (var scope = provider.CreateScope())
{
    var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM