mic*_*cer 4 c# unit-testing entity-framework asp.net-identity asp.net-core
我采用这种方法是为了使单元测试DbContext变得更加容易。这个方法让Context我db记忆深刻。它之所以有效,是因为我用实体对其进行测试(例如_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;
}
Run Code Online (Sandbox Code Playgroud)
我的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);
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,我们可以像使用 那样在内存中创建 Identity UserManager, SignInManager,吗?如何像标准的那样对内存中的用户、角色等进行单元测试?在测试时如何在存储在内存中的假上下文中调用它?RoleManagerIdentityDbContextIdentityContextManagers
编辑:
基于这个 SO Question Identity 共享context,这是显而易见的。但是如何使用Managerson create IdentityDbContextbyUseInMemoryDatabase()方法呢?
编辑2:
我context通过夹具注入:
public class DatabaseFixture
{
public TaskManagerDbContext Context { get; private set; }
public DatabaseFixture()
{
this.Context = DatabaseContextFactory.Create();
}
}
[CollectionDefinition("DatabaseTestCollection")]
public class QueryCollection : ICollectionFixture<DatabaseFixture>
{
}
Run Code Online (Sandbox Code Playgroud)
以及它的用法:
[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);
}
Run Code Online (Sandbox Code Playgroud)
我在用着Xunit。
您需要创建一个服务集合,用它注册所有内容,然后使用它来提取您需要的内容。
var services = new ServiceCollection();
services.AddDbContext<TaskManagerDbContext>(o =>
o.UseInMemoryDatabase(Guid.NewGuid()));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<TaskManagerDbContext>();
var provider = services.BuildServiceProvider();
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用provider:
using (var scope = provider.CreateScope())
{
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1234 次 |
| 最近记录: |