c# - 使用 Asp.Net Boilerplate 进行单元测试时获取新的 DbContext

标签 c# asp.net entity-framework unit-testing asp.net-boilerplate

我正在开发一个基于 Asp.Net Boilerplate 的项目,现在我必须使用具有真实数据库连接(无模拟)的真实存储库对服务进行单元测试。我一直在使用 BringerOd 的最后一篇文章 https://gist.github.com/hikalkan/1e5d0f0142484da994e0作为设置我的 UnitOfWorkScope 实例的指南。所以,我的代码目前看起来像这样:

IDisposableDependencyObjectWrapper<IUnitOfWork> _unitOfWork;

[TestInitialize]
public void SetUpService()
{
    //initialize service

    _unitOfWork = IocManager.Instance.ResolveAsDisposable<IUnitOfWork>();
    UnitOfWorkScope.Current = _unitOfWork.Object;
    UnitOfWorkScope.Current.Initialize(true);
    UnitOfWorkScope.Current.Begin();

}

[TestCleanup]
public void CleanUpService()
{
    UnitOfWorkScope.Current.Cancel();
    _unitOfWork.Dispose();
    UnitOfWorkScope.Current = null;
}

这对于第一个单元测试来说就像一个魅力,但是当我尝试在第二个测试中进行存储库调用时,我得到:“操作无法完成,因为 DbContext 已被释放。”

我的猜测是,当 TestInitialize 方法再次运行时,工作范围单元将分配有相同的(处置的)DbContext,而不是新的。我想,在我的实际测试方法中,我可以在带有 IUnitOfWork 的 using block 中设置我的 UnitOfWorkScope。但是,我真的不想在每个测试中重复该逻辑。有谁知道如何手动获得 using block 的效果,以便我每次都能获得全新的 DbContext?

最佳答案

检查:http://aspnetboilerplate.com/Pages/Documents/Repositories

您必须使用 [UnitOfWork] 属性标记调用方法。

如链接文档中所述,这样做的原因是

When you call GetAll() out of a repository method, there must be an open database connection. This is because of deferred execution of IQueryable<T>. It does not perform database query unless you call ToList() method or use the IQueryable<T> in a foreach loop (or somehow access to queried items). So, when you call ToList() method, database connection must be alive. This can be achieved by marking caller method with the [UnitOfWork] attribute of ASP.NET Boilerplate. Note that Application Service methods are already using [UnitOfWork] as default, so, GetAll() will work without adding the [UnitOfWork] attribute for application service methods.

关于c# - 使用 Asp.Net Boilerplate 进行单元测试时获取新的 DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27539562/

相关文章:

javascript - 每当发生回发时都需要从 .aspx (VB.net) 页面调用 Javascript 函数

wcf - Entity Framework - 架构升级、多个 DBMS 和代码优先

c# - 如何在 xamarin C# 中的 tableLayout 中单击特定行时检索对象

c# - 列表中自动实现的属性有什么作用,它们是如何工作的?

c# - Google Plus API 获取相册/视频

c# - Entity Framework - 如何避免查询重新编译?

c# - Entity Framework : Unable to call stored procedure,错误的代码生成

c# - 如何将复杂对象从 jquery 传递到标记 <a> 中的 Action Controller

c# - 使用C#生成正态分布图

javascript - 如果未填写控件,则自定义验证器不会触发