为多线程环境模拟 Dbcontext 的正确方法



在实体框架中,DBContext 不是 线程安全。为了支持多线程环境,每次需要与 SQL 通信时,我都必须基于连接字符串初始化一个新的 DbContext。

private void function(string sqlConnectionString)
{
using (var dbContext = new DbContext(sqlConnectionString))
{
// talk to sql here
}
}

现在单元测试变得棘手。由于 DbContext 隐藏在代码中,因此我无法传入模拟的 DbContext。

我在网上看了一下,但没有找到一个好的解决方案。有什么建议吗?

为了对此进行单元测试,我将为DbContext创建一个工厂并注入工厂。工厂现在可以被NSubstitute取代。对于单元测试部分,替换的DbContext工厂将返回一个新DbContext,该与内存数据库(如实体框架的工作(的连接

private void function(IDbContextFactory dbContextFactory)
{
using (var dbContext = dbContextFactory.Create())
{
// talk to sql here
}
}

在单元测试的代码中:

//Arrange
var connectionStringForEffortDatabase = ...
var dbCotextFactory = Substitute.For<IDbContextFactory>();
dbContextFactory.Create().Returns(new DbContext(connectionStringForEffortDatabase));
//Act
function(dbContextFactory);
//Assert
Assert.Something():

相关内容

最新更新