【发布时间】:2019-12-16 19:43:26
【问题描述】:
我有一个DbContext,它有一个没有密钥的Dbset。它适用于仅查询表的应用程序。
public class MyDbContext : DbContext, IMyDbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }
public DbSet<MyEntity> MyEntities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>().HasNoKey(); // No key
modelBuilder.ApplyConfigurationsFromAssembly(typeof(MyDbContext).Assembly);
}
}
我在测试项目 (xUnit) 中创建了以下测试设置类:
public static class MyDbContextFactory
{
internal static MyDbContext Create()
{
var options = new DbContextOptionsBuilder<MyDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
var context = new MyDbContext(options);
context.Database.EnsureCreated();
context.MyEnities.AddRange(new[] // This line got the error!!!
{
new MyEntity { Time = DateTime.Now, Instrument = "R1" },
new MyEntity { Time = DateTime.Now, Instrument = "R2" },
new MyEntity { Time = DateTime.Now, Instrument = "R3" },
});
context.SaveChanges();
return context;
}
}
public class QueryTestFixture : IDisposable
{
public MyDbContext MyDbContext { get; }
public IMapper Mapper { get; }
public QueryTestFixture()
{
MyDbContext = MyDbContextFactory.Create();
var configurationProvider = new MapperConfiguration(cfg =>
{
cfg.AddProfile<MappingProfile>();
});
Mapper = configurationProvider.CreateMapper();
}
public void Dispose()
{
// ... omitted ...
}
}
[CollectionDefinition("QueryTests")]
public class QueryCollection : ICollectionFixture<QueryTestFixture> { }
这里是测试代码。
[Collection("QueryTests")]
public class MyTest
{
private readonly MyDbContext _context;
private readonly IMapper _mapper;
public MyTest(QueryTestFixture fixture)
{
_context = fixture.MyDbContext;
_mapper = fixture.Mapper;
}
}
但是,在实际运行测试之前运行任何测试方法都会出现以下错误。错误发生在上面的 context.MyEnities.AddRange(.... 行。
【问题讨论】:
-
你想测试什么?为什么不使用 IMyDbContext 的模拟,而是使用 MyDbContext 的具体实例?
-
您是否尝试过使用
AsNoTracking进行查询? -
@ca9163d9 在真实应用程序 DbSet
上是映射视图还是表? -
@LuttiCoelho,这是一个视图。
-
@PavelAnikhouski,在哪里添加
AsNoTracking?我尝试添加它(` context.MyEnities.AsNoTracking();) right beforecontext.MyEnities.AddRange(...)` 但它仍然出现错误。
标签: c# entity-framework unit-testing xunit