我使用InMemoryDatabase编写测试用例,但当我想测试关系数据库操作(插入/更新)时,我无法使用InMemoryDatabase。
如果我使用InMemoryDatabase,我会遇到如下错误
系统InvalidOperationException:“只有当上下文使用关系数据库提供程序时,才能使用特定于关系的方法。”
有没有办法在不接触开发或生产数据库的情况下测试关系数据库操作(插入/更新)?
这是使用关系数据库操作的repository类
public bool UpdateOrInsert(Model model, Details details = null)
{
//_context is SqlDbContext
using (var transaction = _context.Database.BeginTransaction())
{
try
{
if(details.Id > 0)
{
//Update details;
_context.SaveChanges();
}
else
{
//Insert details;
_context.SaveChanges();
}
if(model.Id > 0)
{
//Update model;
_context.SaveChanges();
}
else
{
//Insert model;
_context.SaveChanges();
}
transaction.Commit();
return true;
}
catch(Exception ex)
{
transaction.Rollback();
throw;
}
}
}
我们如何在不接触真实数据库的情况下编写这种方法的单元测试?有办法吗?
我用来测试这个方法的测试用例抛出了上述错误。
[Fact]
public void CheckTest()
{
DbContextOptions<SqlDbContext> _options;
_options = new DbContextOptionsBuilder<SqlDbContext>()
.UseInMemoryDatabase(databaseName: "DbName1")
.Options;
using (var context = new SqlDbContext(_options))
{
context.Model.Add(_model);//_model= sample model object
context.Details.Add(_details);//_details = sample details object
context.SaveChanges();
var cls = new ClassName();
var result = cls.UpdateOrInsert(_model,_details);
Assert.Assert.IsType<Bool>(result);
}
}
如果我使用以下方法进行检查,就可以更新原始数据库。
[Fact]
public void CheckTest()
{
var connectionString = @"Data Source = *****; Initial Catalog = ******; uid = ****; Pwd = ******";
DbContextOptions<SqlDbContext> _sqlOptions = new DbContextOptionsBuilder<SqlDbContext>()
.UseSqlServer(connectionString)
.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning))
.Options;
using (var context = new SqlDbContext(_sqlOptions))
{
var cls = new ClassName();
var result = cls.UpdateOrInsert(_model,_details);
Assert.Assert.IsType<Bool>(result);
}
}
我们有没有其他方法可以在不接触关系数据库的情况下为方法UpdateOrInsert编写测试用例?
是否可以通过InMemmoryDatabase进行测试?
请帮忙