I believe you have seen companies that run their integration tests on a real instances of SQL Server. This is an old practice that some companies do in order to validate their business logic.
Keeping a database instance has a cost, this can be avoided by running integration tests locally.
On this article, I’m going to show steps on how to run queries for your integration tests.
Sample Project
This WebAPI is our application that the integration test will run over. It’s a simple application with one controller, entity and repository. This application connects to a SQL Server application.
The Program.cs shows the application pointing to a SQL Server.
Using the same DbContext to run SQLite on the Integration Test
Here, I just had to create a class the inherits the DbContext from the main application and overriding OnConfiguring and set it to use UseSqlIte as well the connection string.
The Secret – The WebApplicationFactory class
That’s the excited point on this article, where we use the same DbContext on the Integration Test project.
The WebApplicationFactory is responsible for emulate our Program.cs on the Integration Test, this class can manage both connection database and services injections.
I commented each line of this class so you guys can understand what it does.
Running Migration for SQLite Database
Once you the services all set, it`s time to create the migration SQLite.
On the SQL Integration Test project run the following command:
dotnet ef migrations add FirstMigration --context TestContext
Tests
And this is the test that runs on order. First it calls the post endpoint to create a new Product and then following by the other test that retrieves this inserted record.
Debuging Tests
In this screenshot you can see the debug working when running the tests.
Conclusion
SQLite proves to be a really powerful tool when it comes on Integration tests along with Entity Framework. It works perfectly with migration and the most important, you don’t need to manage anything related to dbContext on the Integration Test project because it ininherits the dbContext from the main Application.
Be aware that SQLite doesn’t support Procedures.
Hope this helps you somehow, thanks.