2.1 KiB
2.1 KiB
name, description
| name | description |
|---|---|
| GenerateIntegrationTest | Guide to creating Integration Tests (end-to-end) using WebApplicationFactory and Testcontainers. |
GenerateIntegrationTest Skill
When a user requests to create an Integration Test to verify API endpoints from start to finish, you need to generate the code according to the following guidelines:
Purpose
- Test whether the assembled components work correctly together.
- Flow: Client calls API -> Middleware -> Controller -> CQRS Handler/Service -> Read/Write to a real Database.
Implementation Guide
-
Setup WebApplicationFactory:
- Automatically setup
WebApplicationFactory<Program>(to create an in-memory test server in .NET). - Override application configurations if necessary (e.g., changing the ConnectionString to point to a test container).
- Automatically setup
-
Setup Testcontainers (Real Database):
- Use the
Testcontainerslibrary (or similar configuration) to automatically spin up a Docker container containing a real Database (e.g., PostgreSQL, SQL Server). - Ensure this database container starts before the tests run and is automatically disposed of after the tests complete. Avoid using in-memory SQLite because it often causes minor bugs and does not accurately mimic a production database.
- Use the
-
Write API Test Scenarios (Arrange - Act - Assert):
- Create an
HttpClientobject fromWebApplicationFactory.CreateClient(). - Arrange: Prepare payload data as JSON objects or prepopulate database records for GET/PUT/DELETE APIs.
- Act: Call the corresponding API endpoint directly via code. E.g.:
await client.PostAsJsonAsync("/api/v1/samples", payload);. - Assert: Verify the returned results:
- Check HTTP Status: is it
200 OKor400 Bad Request? - Deserialize the response body to check the exact object data.
- (Optional) Query the database container directly to confirm the record was actually created/updated.
- Check HTTP Status: is it
- Create an
Output File Format
- Path: Placed in the corresponding test project, such as
tests/MyNewProjectName.IntegrationTests/Controllers/.... - File Name:
[ControllerName]Tests.cs(e.g.,OrdersControllerTests.cs).