我是新来创建服务类的单元测试的。我在上下文中访问视图时遇到了一个问题。我有两个上下文,一个用于写,一个用于阅读。下面是用于阅读的上下文文件的示例。
public class readContext : DbContext
{
private readonly IOptions<DatabaseConfig> _dbConfiguration;
public readContext(IOptions<DatabaseConfig> dbConfiguration)
{
_dbConfiguration = dbConfiguration;
}
public DbSet<AppVM> AppVMs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new AppVMMap());
base.OnModelCreating(modelBuilder);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_dbConfiguration.Value);
}
}
写入上下文:
public class writeContext : DbContext, IUnitOfWork
{
private readonly IOptions<DatabaseConfig> _dbConfiguration;
public static readonly LoggerFactory _myLoggerFactory =
new LoggerFactory(new[] {
new DebugLoggerProvider()
});
public writeContext(IOptions<DatabaseConfig> dbConfiguration)
{
_dbConfiguration = dbConfiguration;
}
public writeContext(DbContextOptions _dbConfiguration) : base(_dbConfiguration)
{
}
public DbSet<Sample1> Sample1 { get; set; }
public DbSet<Sample2> Sample2 { get; set; }
public DbSet<Sample3> Sample3 { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new sample1Map());
modelBuilder.ApplyConfiguration(new sample2Map());
modelBuilder.ApplyConfiguration(new sample3Map());
base.OnModelCreating(modelBuilder);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(_myLoggerFactory);
}
public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await base.SaveChangesAsync();
return true;
}
}
在单元测试-设置方法中,我试图创建一个内存数据库来访问上面的上下文.
var writeBuilder = new DbContextOptionsBuilder<writeContext>().UseInMemoryDatabase(databaseName: "Sample").EnableSensitiveDataLogging(true);
_writeContext = new writeContext(writeBuilder.Options);
var builder = new DbContextOptionsBuilder<readContext>().UseInMemoryDatabase(databaseName: "Sample") .EnableSensitiveDataLogging();
var context = new readContext(builder.Options);
但在此之后,我完全空白,不知道如何访问的意见。因此,可以模拟DB和Access视图。任何帮助都将不胜感激
1条答案
按热度按时间monwx1rj1#
在Entity Framework Core中,您可以使用DbContext创建自定义查询,以访问单元测试中的视图。您可以尝试以下代码,看看它是否对您有帮助。如果有任何问题,请告诉我。
在DbContext类中,创建从视图返回数据的自定义查询方法。
在单元测试方法中,使用自定义查询方法从视图访问数据。
本示例假定AppVM是表示视图结构的类或模型。将其替换为适当的类名。