Integration Testing APIs
Integration Testing APIs
Integration testing is a form of automated testing.
Contrary to unit tests, we don’t test a single code unit (such as classes) independent from other units, but we test the interaction of multiple units and how well they integrate.
When to use integration tests
The opinions when to use integration testing and when to use unit testing differ a bit depending who you ask.
Most of the time it is stated, that you should use integration tests and unit tests together to have the best test coverage.
Using Integration tests for APIs
When doing integration tests with APIs we typically want to test the complete data flow including a HTTP Request, all the logic that happens on the server and the response.
We therefore need a way of accessing the service while it is running from the integration test.
How To
- We assume that there is an existing WebApi or MinimalApi project in your C# Solution.
- Create a new unit test project.
- Install the NuGet Package
Microsoft.AspNetCore.Mvc.Testing
in the unit test project.
How To (2)
- Inside your unit test classes you can use an instance of a HttpClient to access the API.
WebApplicationFactory
is a type imported from the NuGet PackageMicrosoft.AspNetCore.Mvc.Testing
.Program
references the class Program in your WebApi or MinimalApi project. It therefore needs to be publicly available, so the unit test project can reference it.
How To (3)
- A simple integration test might look like this: