我设计了这个方法,让单元测试
我的问题是,我们能否像使用
编辑:根据这个SO问题,很明显,Identity共享上下文
编辑2:我正在通过夹具注入
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);
}
}
我的问题是,我们能否像使用
IdentityDbContext
一样,将Identity的UserManager
、SignInManager
和RoleManager
存储在内存中?如何在内存中对用户、角色等Identity
内容进行单元测试,就像我们可以使用标准的Context
一样?如何在存储在内存中的虚拟上下文中调用这些Managers
?编辑:根据这个SO问题,很明显,Identity共享上下文
context
。但是如何在UseInMemoryDatabase()
方法创建的IdentityDbContext
中使用Managers
呢?编辑2:我正在通过夹具注入
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
。
InMemory
数据库上使用相关的Managers
吗?我可以在我的Fixture
类中实现它吗? - michasaucerprovider
,然后使用我上面所做的方法,在CreateScope
中包装你的测试。 - Chris Prattusing (var scope = provider.CreateScope())
吗?如果不需要,你能告诉我如何在这个作用域中模拟用户以在所有测试class
中使用吗? - michasaucer