Is there an in-memory provider for Entity Framework?

夙愿已清 提交于 2019-11-27 21:48:29

There is not currently a in memory provider for EF, but if you take a look at Highway.Data it has a base abstraction interface and an InMemoryDataContext.

Testing Data Access and EF with Highway.Data

Shimmy

An InMemory provider is included in EF7 (pre-release).

You can use either the NuGet package, or read about it in the EF repo on GitHub (view source).

Michael Freidgeim

The article http://www.codeproject.com/Articles/460175/Two-strategies-for-testing-Entity-Framework-Effort  describes Effort  -Entity Framework provider that runs in memory.

You can still use your DbContext or ObjectContext classes within unit tests, without having to have an actual database.

A better approach here might be to use the Repository pattern to encapsulate your EF code. When testing your services you can use mocks or fakes. When testing your repositories you will want to hit the real DB to ensure that you are getting the results you expect.

Yes, there is at least one such provider - SQLite. I have used it a bit and it works. Also you can try SQL Server Compact. It's an embeded database and has EF providers too.
Edit:
SQLite has support for in-memory databases (link1). All you need is to specify a connection string like: "Data Source=:memory:;Version=3;New=True;". If you need in an example you may look at SharpArchitecture.

I am not familiar with Entity Framework and the ObjectQuery class but if the Include method is virtual you can mock it like this:

// 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);

You could try SQL Server Compact but it has some quite wild limitations:

  • SQL Server Compact does not support SKIP expressions in paging queries when it is used with the Entity Framework
  • SQL Server Compact does not support entities with server-generated keys or values when it is used with the Entity Framework
  • No outer joins, collate, modulo on floats, aggregates

In EF Core there are two main options for doing this:

  1. SQLite in-memory mode allows you to write efficient tests against a provider that behaves like a relational database.
  2. The InMemory provider is a lightweight provider that has minimal dependencies, but does not always behave like a relational database

I am using SQLite and it supports all queries, that I need to do with Azure SQL production database.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!