代码之家  ›  专栏  ›  技术社区  ›  Michael L Perry

实体框架是否有内存中的提供程序?

  •  35
  • Michael L Perry  · 技术社区  · 16 年前

    我是针对ADO.NET实体框架编写的单元测试代码。我想用行填充内存中的数据库,并确保我的代码正确地检索它们。

    我可以使用Rhino模拟来模拟实体框架,但这还不够。我将告诉这个问题,哪些实体将返回给我。这既不会测试WHERE子句,也不会测试.include()语句。我想确保我的WHERE子句只匹配我想要的行,而不匹配其他行。我想确定我已经要求了我需要的实体,没有一个是我不需要的。

    例如:

    class CustomerService
    {
        ObjectQuery<Customer> _customerSource;
        public CustomerService(ObjectQuery<Customer> customerSource)
        {
            _customerSource = customerSource;
        }
        public Customer GetCustomerById(int customerId)
        {
            var customers = from c in _customerSource.Include("Order")
                where c.CustomerID == customerId
                select c;
            return customers.FirstOrDefault();
        }
    }
    

    如果我模拟ObjectQuery返回一个填充了订单的已知客户,我如何知道CustomerService有权使用WHERE子句和INCLUDE?我宁愿插入一些客户行和订单行,然后断言选择了正确的客户并填充了订单。

    8 回复  |  直到 7 年前
        1
  •  7
  •   Devlin Liles    10 年前

    当前没有内存中的ef提供程序,但是如果您查看highway.data,它有一个基本抽象接口和一个inmemoryDataContext。

    Testing Data Access and EF with Highway.Data

        2
  •  16
  •   Denis Biondic    9 年前

    InMemory提供程序包含在 EF7 (预发布)。

    您可以使用 NuGet package 或在 EF repo 吉瑟布论 view source )

        3
  •  13
  •   John Cummings    7 年前

    文章 http://www.codeproject.com/Articles/460175/Two-strategies-for-testing-Entity-Framework-Effort 描述_ Effort -在内存中运行的实体框架提供程序。

    您仍然可以在单元测试中使用_dbContext或_objectcontext_类,而无需实际的数据库。

        4
  •  9
  •   Andrew Peters    16 年前

    这里更好的方法可能是使用存储库模式来封装EF代码。当测试您的服务时,您可以使用模拟或伪造。在测试存储库时,您将希望访问真实的数据库,以确保获得预期的结果。

        5
  •  6
  •   zihotki    16 年前

    是的,至少有一个这样的提供者- SQLite . 我用过一点,它也能用。你也可以试试 SQL Server Compact . 它是一个嵌入式数据库,也有EF提供者。
    编辑:
    sqlite支持内存中的数据库( link1 )您只需要指定一个连接字符串,如:“数据源=:内存:;版本=3;新=真;”。如果你需要一个例子,你可以看看 SharpArchitecture .

        6
  •  2
  •   Darin Dimitrov    16 年前

    我不熟悉实体框架和ObjectQuery类,但是如果include方法是虚拟的,您可以这样模拟它:

    // Arrange
    var customerSourceStub = MockRepository.GenerateStub<ObjectQuery<Customer>>();
    var customers = new Customer[] 
    {
        // Populate your customers as if they were coming from DB
    };
    customerSourceStub
        .Stub(x => x.Include("Order"))
        .Return(customers);
    var sut = new CustomerService(customerSourceStub);
    
    // Act
    var actual = sut.GetCustomerById(5);
    
    // Assert
    Assert.IsNotNull(actual);
    Assert.AreEqual(5, actual.Id);
    
        7
  •  1
  •   Chris S    16 年前

    你可以试试 SQL Server Compact 但它有一些相当大的局限性:

    • 当与实体框架一起使用时,SQL Server Compact不支持分页查询中的跳过表达式。
    • 当与实体框架一起使用时,SQL Server Compact不支持具有服务器生成的键或值的实体
    • 没有外部联接、排序、浮点数模、聚合
        8
  •  0
  •   Michael Freidgeim    7 年前

    EF Core 执行此操作有两个主要选项:

    1. SQLite in-memory mode 允许您针对行为类似于关系数据库的提供程序编写有效的测试。
    2. The InMemory provider 是一个轻量提供程序,它具有最小的依赖关系,但并不总是表现得像关系数据库。

    我使用的是sqlite,它支持所有的查询,这是我需要用AzureSQL生产数据库做的。