Reputation: 31
I am using ef core in project and my repository calls a stored procedure to get the results. I was wondering if I can use inMemorydatabase feature of ef core to test against my repository.
Upvotes: 2
Views: 1278
Reputation: 69928
You can but you should not do it. From Microsoft:
EF Core comes with an in-memory database that we use for internal testing of EF Core itself. This database is in general not suitable for testing applications that use EF Core. Specifically:
- It is not a relational database.
- It doesn't support transactions.
- It cannot run raw SQL queries.
- It is not optimized for performance.
None of this is very important when testing EF Core internals because we use it specifically where the database is irrelevant to the test. On the other hand, these things tend to be very important when testing an application that uses EF Core.
https://learn.microsoft.com/en-us/ef/core/testing/#approach-3-the-ef-core-in-memory-database
Microsoft recommends using SQLite in-memory database instead. Always remember its lifetime though:
Sample:
public class SqliteInMemoryItemsControllerTest : ItemsControllerTest, IDisposable
{
private readonly DbConnection _connection;
public SqliteInMemoryItemsControllerTest()
: base(
new DbContextOptionsBuilder<ItemsContext>()
.UseSqlite(CreateInMemoryDatabase())
.Options)
{
_connection = RelationalOptionsExtension.Extract(ContextOptions).Connection;
}
private static DbConnection CreateInMemoryDatabase()
{
var connection = new SqliteConnection("Filename=:memory:");
connection.Open();
return connection;
}
public void Dispose() => _connection.Dispose();
}
https://learn.microsoft.com/en-us/ef/core/testing/sqlite#using-sqlite-in-memory-databases
Upvotes: 2