Skip to content
Back to skills

Api Testing

ASecurity

Mandatory conventions for authoring .NET 10 + xUnit API integration tests for the project's HTTP services using the shared integration test framework. Here, "integration testing" = API testing (over-the-wire tests of deployed services) and it lives under tests/integration/. Trigger words include api test, api tests, integration test, integration tests, microservice integration test, microservice api test, service tests, http test, endpoint test, endpoint integration test, contract test, healt...

  • 2 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 4, 2026
developmentgobashsqltestingapidatabasefrontendbackendperformance

Works with

  • cli
  • api

Security analysis

A100/100

Scanned December 4, 2026

npx -y skills add elhajahmadj/SDLCskill --skill api-testing --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Api Testing?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Api Testing
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/elhajahmadj-api-testing/badge)](https://www.skillsdirectory.com/skills/elhajahmadj-api-testing)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: api-testing
description: Mandatory conventions for authoring .NET 10 + xUnit API integration tests for the project's HTTP services using the shared integration test framework. Here, "integration testing" = API testing (over-the-wire tests of deployed services) and it lives under tests/integration/. Trigger words include api test, api tests, integration test, integration tests, microservice integration test, microservice api test, service tests, http test, endpoint test, endpoint integration test, contract test, health endpoint test, smoke api test, scaffold integration test project, scaffold api test project, add a service fixture, add typed client, service client, appsettings, xunit, fluentassertions, integration framework, run the integration tests.
---

# API Integration Tests — Mandatory Conventions

> **Namespace placeholder:** `App` is a placeholder for the real project namespace root chosen at project-init
> (e.g. `App.Automation.Shared`, `App.<Service>.IntegrationTests`). Substitute the actual project name wherever
> you see `App`.
>
> **Here, "integration tests" = API tests** — over-the-wire tests of deployed HTTP services
> (real network, real service, real database behind it). They live at `tests/integration/`.
> This file is the rulebook enforced on every change.

This skill guarantees that API/integration tests follow the same architecture, fixture model,
config layering, naming, and pinned versions, respecting **SOLID / DRY / YAGNI / clean
architecture**, with shared framework code kept strictly separate from service-specific test
code. Treat it as **mandatory** whenever it applies.

## When this skill applies

Use for API / integration automation work: add an integration or API test · add a test method ·
add a new suite · scaffold a new **service** integration test project · create a typed client ·
add request/response contracts · add a service fixture · create smoke tests for a service ·
write xUnit API tests · run the integration tests (§14).

**Do NOT apply for:** UI/Playwright functional tests (`functional-testing`, under
`tests/functional/`) · backend unit tests (`backend-unit-tests`, under `tests/back-end unit/`) ·
production API code · frontend code · performance/load tests.

## Core principles — enforce on every change

**SOLID** — one primary reason to change per class. Service-specific logic stays out of `Shared`
and `Infrastructure`. Favor composition over speculative inheritance.
**DRY** — exactly one of each: config-loading pipeline · fixture pattern · HTTP execution
abstraction · serializer-options factory · response wrapper · typed-client base.
**YAGNI** — do not add unless explicitly requested: retry frameworks · custom DSLs · reporting
engines · reflection auto-generation · elaborate auth orchestration beyond current needs.
**Clean architecture:**
- `App.Automation.Shared` = config models + loading, validation, guards, serialization **only**.
- `App.Automation.Infrastructure` = fixtures, HTTP plumbing, DI, typed-client base, generic assertions **only**.
- `App.<Service>.IntegrationTests` = routes, typed clients, DTOs, fixtures, tests **only** (config is centralized).

## Required layout (follow exactly)

```text
tests/integration/
├── App.Automation.sln
├── appsettings.json            # centralized config for ALL services (Services: section)
├── appsettings.Local.json      # per-developer overrides
├── Directory.Packages.props    # Central Package Management: every version pinned once
├── Directory.Build.targets     # links the central config into each test project's output
├── parallel.runsettings        # MaxCpuCount=0 — one host process per project
├── docs/Examples.md
├── App.Automation.Shared/
├── App.Automation.Infrastructure/
└── Services/                                    # grouping folder = the integration dimension (service)
    ├── App.<ServiceA>.IntegrationTests/
    └── App.<ServiceB>.IntegrationTests/
```

Reference chain, **one way only**:
`App.<Service>.IntegrationTests → App.Automation.Infrastructure → App.Automation.Shared`
Service projects never reference each other; `Shared` never references `Infrastructure` or a
service project; `Infrastructure` never references a service project.

### Required folders in every service project (create all on creation)
```text
App.<Service>.IntegrationTests/
├── Config/          # optional code; folder exists for collection fixtures/config helpers
├── Constants/       # ALWAYS: ApiEndpoints.cs, TraitNames.cs
├── Clients/         # one interface + one implementation per client
├── Contracts/{Requests,Responses}/
├── Fixtures/        # ALWAYS: <Service>ApiFixture.cs, <Service>ApiTestBase.cs
└── TestSuites/      # test classes ONLY (ALWAYS a HealthTests.cs wiring proof)
```
Service projects do **not** own `appsettings*.json`. A new project is not complete without both
fixture files, at least one typed client (usually health), and a passing smoke test.

## Exact namespaces (mirror project + folder)
```csharp
namespace App.Automation.Shared.{Configuration,Validation,Helpers,Serialization};
namespace App.Automation.Infrastructure.{Abstractions,Auth,Http,Fixtures,DependencyInjection,Assertions};
namespace App.<Service>.IntegrationTests.{Constants,Clients,Contracts.Requests,Contracts.Responses,Fixtures,TestSuites};
```
HTTP execution only under `.Http`; fixtures only under `.Fixtures`; DI only under
`.DependencyInjection`; generic response assertions only under `.Assertions`. Never a client in
`.TestSuites`, a test class in `.Clients`, or a DTO outside `Contracts`.

---

## Mandatory rules

### 1. Central Package Management — no inline versions
`tests/integration/Directory.Packages.props` sets `ManagePackageVersionsCentrally=true`.
- A `PackageReference` that **also carries `Version=` is NU1008 — an error**; restore fails. Every csproj is bare.
- New package? add `<PackageVersion Include Version />` to the central file. Never float/wildcard.
- **Never upgrade FluentAssertions above `7.2.0`** (8.0 is commercial). **Never swap xUnit for NUnit.**
- `Microsoft.Extensions.*` must **match or exceed** what the application pins (a lower direct pin than the transitive requirement is **NU1605 — an error**).
- No per-project appsettings files or per-project copy items.
Pins: `xunit` 2.9.3 · `xunit.runner.visualstudio` 3.1.5 · `xunit.analyzers` 1.27.0 ·
`Microsoft.NET.Test.Sdk` 18.6.0 · `FluentAssertions` 7.2.0 · `coverlet.collector` 10.0.1 ·
`Microsoft.Extensions.*` 10.0.10 · TFM `net10.0`.

### 2. Configuration — one centralized file, `Services` section
Exactly one config pair at `tests/integration/`: `appsettings.json` (every service under a single
`Services` section keyed by service name) + `appsettings.Local.json`. Linked into each project's
output by `Directory.Build.targets` (gated on `'$(IsTestProject)'=='true'`), so the loader finds
them in `AppContext.BaseDirectory`. Scaffolding a service → **add a `Services:<Service>` entry**,
never a config file. Override order: `appsettings.json` → `appsettings.Local.json` → env vars.
- Config loaded through the shared framework **only** (no ad-hoc `ConfigurationBuilder` in a test).
- No hardcoded service URLs. Config is **strongly typed**. Required config **validated at fixture init** with a message naming the missing key **and** the service.
- **Secrets never committed** — empty fields, supplied via env vars with a **prefix distinct from the app's** (e.g. `TESTS_AUTH__CLIENTSECRET`) so suite and app can't collide on one machine.

### 3. Test method naming (mandatory)
```text
Given_<Precondition>_When_<Action>_Then_<ExpectedOutcome>_Async
```
Must begin `Given_`, include `When_`, include `Then_`, end `_Async`; business language; **no
test-case/ticket IDs in the name** (the UI suite prefixes `Tc<id>_`; integration does not); no
spaces/hyphens/random suffixes.

### 4. Trait rules (mandatory)
Every test has ≥1 xUnit trait; names/values come from `Constants/TraitNames.cs` (`Category` +
nested `Categories` consts: Smoke, Health, Negative, Regression, …). No inline magic trait
strings — add the constant to `TraitNames` first.

### 5. Exact fixture inheritance
```text
IntegrationTestFixture (framework) → <Service>ApiFixture (service, sealed, overrides ServiceKey, registers clients)
IntegrationTestBase<TFixture> (framework) → <Service>ApiTestBase (service, thin) → the service's test classes
```
`IntegrationTestFixture : IAsyncLifetime` loads+validates config, resolves `ServiceKey`, builds the
`HttpClient`, applies headers + optional auth, exposes `Services`/`Client`/`Config`/`ServiceConfig`/
`SerializerOptions`, owns lifecycle. `<Service>ApiFixture` is `sealed`, **must** override `ServiceKey`
and register typed clients in `ConfigureServices`, and **must not** duplicate base init. Once
`<Service>ApiTestBase` exists, no test inherits `IntegrationTestBase<T>` directly.

### 6. Typed clients — exact naming
Interface `I<Feature>ApiClient`, impl `<Feature>ApiClient`, files match type names, namespace
`…IntegrationTests.Clients`. Each impl inherits `ServiceClientBase`, uses `ApiEndpoints` constants
and the shared request-execution abstraction, and is **assertion-free**. Method names = HTTP intent
+ resource intent, `Async`-suffixed (`GetHealthAsync`, `GetOrderByIdAsync`, `CreateOrderAsync`);
never `Http` in the name, never the full route, never vague `SendAsync`/`ExecuteAsync`. **One
coherent resource area per client** (`HealthApiClient`, `OrdersApiClient`; not `EverythingApiClient`).
Decision rule: if adding an endpoint would make the client own more than one domain concept, make a new client.

### 7. Route centralization
All routes in `Constants/ApiEndpoints.cs` (consts + parameterized helper **methods**). No raw route
strings in tests/clients; never duplicate a route string.

### 8. DTO placement
Request DTOs → `Contracts/Requests/`; response DTOs → `Contracts/Responses/`. Never a
service-specific DTO in `Shared`/`Infrastructure` (only genuinely universal DTOs go in `Shared`).

### 9. Test design — the assertion bar per endpoint
Resolve typed clients from the fixture's `Services` in the test-class constructor; keep assertions
in tests; one scenario per test. A suite is not done until (or the miss is stated with a reason):
- **Exact success status** (200/201/204) — not merely `IsSuccessStatusCode`.
- **Response body contract:** the members that matter are present, typed, echo what was sent.
- **Round-trip:** GET after POST returns the created resource.
- **Persistence** via the fixture's EF access (§10) where relevant.
- **400** one representative case per validation-failure class (rule-by-rule stays in unit tests).
- **401** unauthenticated · **403** authenticated-without-policy + another tenant's id · **404** unknown id · **409** where defined.
- **List endpoints:** paging, filtering, sorting, empty result.
- **No `5xx` on bad input** — a malformed payload must produce 4xx; a 500 is a defect.

### 10. Database access — opt-in per fixture + trait per test (both mandatory) — *future capability*
The EF-Core DB-verification capability (fixture `DatabaseContexts` gate + per-test
`[Trait(Category, DbContextNames.<Ctx>)]` gate, resolved via `Fixture.GetDatabaseService<TContext>(Output)`,
EF Core only, never `EnsureCreated`/`Migrate`, `ClientSecretCredential` token — no SQL passwords) may not
yet be built in `tests/integration`. Wire it exactly this way when added; it shares the
data-access project with the functional suite — extend, never fork.

### 11. Test data factories + automatic cleanup — *pairs with §10*
When DB access exists: any test that inserts data builds entities from a shared `{Service}TestData`
factory (never inline); every generated row embeds the `Automation` marker in a searchable column;
after the fixture disposes, marked rows are swept via EF `ExecuteDeleteAsync`, gated by
`AutomationDatabase:CleanupAfterRun`, best-effort, never failing a green run.

### 12. Email verification — `EmailServiceRqrd` — *future capability*
Fixture `RequiresEmailService => true` + `[Trait(Category, AutomationTestCategories.EmailServiceRqrd)]`.
**xUnit has no per-test fixture hook**, so open the mailbox session **in the test body, before the
action** (via `Fixture.OpenMailboxAsync(Output)`). Assert on the `EmailMessage` DTO; isolate with a
unique alias + `ReceivedAfter` stamped before the action; serialize across processes. May not yet be built.

### 13. Framework unit-test coverage
Any change to `App.Automation.{Shared,Infrastructure}` (executor, `ServiceClientBase`, assertions,
DI, auth, config, guards, serializer factory) or the shared data-access/email project **must** be
matched by an added/updated hermetic unit test in the same change, or the gap documented.

---

### 15. Cross-service effects are eventual — poll with a deadline

The services coordinate through RabbitMQ events, so an effect in **another** service (a derived charge, an
eligibility change, a notification, an erasure confirmation) lands moments after the call
returns. Assert it by **polling the owning service's API until a deadline** (a private `WaitFor…Async` with
`DeliveryTimeout` / `PollInterval` constants, as in a cross-service events test suite); never `Task.Delay` a fixed time
and never read the other service's tables. Keep the deadline well under any cache TTL the test is meant to beat.
Broker outages and kills are `Category=Chaos` tests (`ChaosFact`, `chaos.runsettings`), excluded from the normal run.

## Forbidden patterns (reject in review)
**Architecture:** service logic in `Shared`/`Infrastructure`; service→service reference; `Shared`→
`Infrastructure`; assertions in a client/`ServiceClientBase`/fixture; a test inheriting
`IntegrationTestBase<T>` when `<Service>ApiTestBase` exists; a second HTTP path (`new HttpClient()`
or `client.SendAsync` in a test).
**Config:** per-project appsettings or copy item; `new ConfigurationBuilder()` in a test;
hardcoded URL; committed secret.
**Packages:** inline `Version=` (NU1008); FluentAssertions 8.x; floating/wildcard version.
**Tests:** raw route where an `ApiEndpoints` const belongs; inline trait string; a test with no
category trait; `IsSuccessStatusCode` as the only assertion; a test-case/ticket ID in a name;
`Thread.Sleep`/wall-clock wait; a `[Fact]` asserting several behaviors (create+update+delete in one).

---

## Recipes

### A — add a test method to an existing suite
1. Confirm the route is in `ApiEndpoints`; confirm a typed client method exists (add to the right client per §6 — interface + impl — if not).
2. Add request/response DTOs under `Contracts/` if the shapes are new.
3. Add the `[Fact]`/`[Theory]` with ≥1 `TraitNames` category + a `Given_…_When_…_Then_…_Async` name.
4. Assert to the §9 bar (exact status, body contract, negative case where relevant).

### B — add a new typed client
`Clients/I<Feature>ApiClient.cs` + `<Feature>ApiClient.cs : ServiceClientBase`; add routes to
`ApiEndpoints`; DTOs under `Contracts/`; register in the fixture's `ConfigureServices`; add a suite.

### C — scaffold a new service integration test project
1. `cd tests/integration/Services && dotnet new xunit -n App.<Service>.IntegrationTests -f net10.0`
2. Replace the csproj: bare `PackageReference`s (no versions), `IsTestProject=true`, references to `Infrastructure` + `Shared`, **no appsettings items**.
3. Create all folders. Add a `Services:<Service>` entry to the **central** `appsettings.json` (no config file).
4. `Constants/ApiEndpoints.cs` (health at minimum) + `TraitNames.cs`; `Contracts/Responses/HealthResponse.cs` (members optional).
5. `Clients/IHealthApiClient.cs` + `HealthApiClient.cs`.
6. `Fixtures/<Service>ApiFixture.cs` (override `ServiceKey`, register clients) + `<Service>ApiTestBase.cs`.
7. `TestSuites/HealthTests.cs` and **prove it green before writing anything else.**
8. Register the project in `App.Automation.sln`.

---

## Pre-merge checklist
- [ ] Layout + namespaces match; all folders exist in any new service project; reference chain one-way.
- [ ] No inline `Version=`; FluentAssertions still `7.2.0`.
- [ ] No per-project appsettings; config changes went into the central file. No committed secret (prefixed env vars).
- [ ] Every test name `Given_…_When_…_Then_…_Async`; no IDs in names. Every test has a `TraitNames` category; no inline trait strings.
- [ ] Every new route in `ApiEndpoints`; typed clients correctly named, inherit `ServiceClientBase`, assertion-free, one resource area each.
- [ ] Test classes inherit `<Service>ApiTestBase`. Assertions hit the §9 bar (exact status, body, round-trip, 400/401/403/404/409); no `IsSuccessStatusCode`-only; no 5xx-as-expected for bad input.
- [ ] DB/email tests (when added) carry both gates; EF Core only; inserted data via `{Service}TestData` + `Automation` marker.
- [ ] Framework changes matched by unit tests (or gap documented); project builds green, no new warnings.

---

## §14 Running the tests (incl. Replit / headless container)
Needs **no browser** — the easy suite to run in a container; needs network reachability to the
target deployment + the §2 secret env vars.
```bash
cd tests/integration
dotnet build App.Automation.sln -tl:off                     # build FIRST (cold dotnet test times out)
dotnet test Services/App.<Service>.IntegrationTests/App.<Service>.IntegrationTests.csproj --no-build -tl:off
dotnet test <proj> --no-build --filter "FullyQualifiedName~HealthTests" -tl:off
dotnet test App.Automation.sln --no-build --settings parallel.runsettings -tl:off   # one host process per project
```
**Trait filters — xUnit uses `Category=` (not `TestCategory=`):**
`--filter "Category=Smoke"` · `--filter "Category=Smoke|Category=Health"` ·
`--filter "Category!=EmailServiceRqrd"`.
Capture output reliably (the .NET logger swallows inline `echo $?`):
`(dotnet test <proj> --no-build -tl:off > /tmp/itest.log 2>&1; echo "RC=$?" >> /tmp/itest.log); tail -40 /tmp/itest.log`.
A runsettings XML comment must not contain a double-dash. **Note:** green runs need the target
services reachable (all services + the database); CI compile-gates the suite.

### Troubleshooting
| Symptom | Cause / fix |
|---|---|
| `No configuration found for service 'X'` | Missing `Services:X` entry in the central appsettings, or `ServiceKey` mismatch. |
| Restore fails **NU1008** | A `PackageReference` has an inline `Version=`. Remove it; pin centrally. |
| Restore fails **NU1605** | A direct pin is lower than a transitive requirement; raise it to match/exceed. |
| TLS/certificate errors everywhere | Local self-signed dev cert — set `AllowInvalidCertificates: true` in `appsettings.Local.json` only. |
| `403` where `200` expected | Usually a real authz finding — check token scopes + the id's tenant before changing the test. |

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.