I am trying to set up integration testing between the repository and database for a .NET Framework app, which has already been built. I have been trying to find a way to setup and seed a test database or in memory database that I could use to run some tests against, but don't see much in terms of .NET Framework apps.
I have seen that there is a Microsoft.EntityFrameworkCore.InMemory library that accomplishes what I need, but it is only available for .NET Core projects running version 6.0. I have also found little to no similar mention of this being possible on a .NET Framework Project, but imagine that there has to be a way.
My work on this legacy app is my first foray into the .NET world, so I may be misunderstanding things from my research on this topic. Is it possible to set up a test/in memory database for integration testing a .NET Framework app? If so, what are the best practices for doing so?
CodePudding user response:
If you really want to test a pure SQL database, my advice would be to setup a local MSSQL Server for testing your application and its integration with the database. I don't know what kind of project you have, but assuming it is a ASP.NET project (Web API p.e) you should already have well defined Models which work like the building blocks of the tables you will use on your database. EF Core essentially maps those models as tables in the database.
Define a new connection to a local MSSQL Server
1. Define the service on Startup.cs
using Microsoft.EntityFrameworkCore;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DatabaseContext>(opt => opt
.UseSqlServer(_config.GetConnectionString("Name"), builder =>
{
builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
}));
}
The EnableRetryOnFailure will make sure your application retries a connection to the database server in case of a connection error.
2. Define a ConnectionString
Go to appsettings.json and add
"ConnectionStrings": {
"Name": "Server=(localdb)\\MSSQLLocalDB;Database=myDb;Trusted_Connection=true"
}
This example uses Windows authentication, but you can use SQL Server Authentication
3. Install MSSQL Server Management Studio
It helps a lot for visualizing your database tables
Entitiy Framework in-memory is available for .NET 5.0. My advice to use a local database instance with MSSQL is Microsoft's own recommendation, as mentioned in their website
The EF in-memory database often behaves differently than relational databases. Only use the EF in-memory database after fully understanding the issues and trade-offs involved, as discussed in Testing code that uses EF Core.
