Skip to content
Back to skills

Backend Unit Tests

ASecurity

Mandatory conventions for authoring backend unit tests (xUnit + FluentAssertions 7.2.0 + Moq + Bogus, .NET 10) — hermetic, deterministic tests of service and domain logic. The backend is loosely coupled event-driven services (App.Service.* + EF Core repositories; events via IEventPublisher outbox + IEventHandler inbox over RabbitMQ; may share one AppDbContext until a schema-per-service split), NOT CQRS/MediatR/MassTransit. Tests live under tests/back-end unit/. Trigger words include backend u...

  • 2 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 4, 2026
ai-agentsgobashsqlnodeexpresstestingapifrontendbackend

Works with

  • cli
  • api

Security analysis

A100/100

Scanned December 4, 2026

npx -y skills add elhajahmadj/SDLCskill --skill backend-unit-tests --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Backend Unit Tests?

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

Security grade badge for Backend Unit Tests
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/elhajahmadj-backend-unit-tests/badge)](https://www.skillsdirectory.com/skills/elhajahmadj-backend-unit-tests)

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: backend-unit-tests
description: Mandatory conventions for authoring backend unit tests (xUnit + FluentAssertions 7.2.0 + Moq + Bogus, .NET 10) — hermetic, deterministic tests of service and domain logic. The backend is loosely coupled event-driven services (App.Service.* + EF Core repositories; events via IEventPublisher outbox + IEventHandler inbox over RabbitMQ; may share one AppDbContext until a schema-per-service split), NOT CQRS/MediatR/MassTransit. Tests live under tests/back-end unit/. Trigger words include backend unit test, service unit test, handler test, command test, query test, validator test, domain entity test, value object test, TestCommon, Fakers, TestData, FixedTimeProvider, InMemoryDb, unit test this service, add or update a unit test for the backend, run the unit tests. Do NOT use for UI/functional tests or API/integration tests.
---

# Backend Unit Tests — Mandatory Conventions

> **Namespace placeholder:** `App` is a placeholder for the real project namespace root chosen at project-init
> (e.g. `App.Service.Identity`, `AppDbContext`, `App.TestCommon`). Substitute the actual project name wherever
> you see `App`.
>
> The backend is **loosely coupled, event-driven services** (see the project's event-driven-microservices decision
> record): `App.Service.*` services + EF Core repositories (which may still share ONE `AppDbContext` until a later
> schema-per-service split), an `IUnitOfWork` transaction seam, and the project's own messaging: services **stage**
> events with `IEventPublisher` (outbox) and **consume** them with `IEventHandler<T>` (inbox). It is **NOT** CQRS —
> there is no MediatR/`IRequestHandler`, no MassTransit/`IPublishEndpoint`/`ConsumeContext`, and no `<Svc>.Application`/
> `<Svc>.Domain` split. So the generic spec's **per-service "trio"**, its `IUnitOfWork`+`IPublishEndpoint`+
> `ConsumeContext` mock factories, its command/query/consumer-handler patterns, and its
> `<Svc>.Domain.UnitTests` **DO NOT apply here**. Tests mock a service's **repositories** directly and
> assert on the service's outcome + repository interactions. Tests live under `tests/back-end unit/`; the
> living index is `tests/back-end unit/README.md` — read it for the coverage matrix + documented gaps.

## When this skill applies

Trigger for **backend** unit-test work:
- "unit test this service / method / branch" in a `App.Service.*` service, or a domain entity/value object.
- "add or update the unit test for X" after changing backend service/domain code.
- any change under `tests/back-end unit/**`.
- "run the backend unit tests" — §11.

**Do NOT apply for:** UI/functional (Playwright) tests → `functional-testing`; API/integration tests →
`api-testing`; the automation frameworks' own plumbing; any change under `src/` or the frontend
(production code is **never** edited to enable a test — rule 7).

## Layout (no per-service CQRS trio)

```text
tests/back-end unit/
├── Directory.Build.props            — shared TFM/Nullable/ImplicitUsings/IsPackable
├── Directory.Packages.props         — Central Package Management: every version pinned once
├── README.md                        — coverage matrix + documented gaps register
├── App.TestCommon/                  — shared helpers (NOT a test project). Fakers (seeded Bogus),
│                                       FixedTimeProvider, InMemoryDb (over the shared AppDbContext),
│                                       RecordingEventPublisher (+ .Should()), EventDelivery.
├── App.Infrastructure.UnitTests/
├── App.Service.Identity.UnitTests/  — per-project Fixtures/TestFixtureBase + Builders (service-specific)
├── App.Service.Billing.UnitTests/
├── App.Service.Messaging.UnitTests/
└── App.Service.Notifications.UnitTests/
```

- **One shared `App.TestCommon`** (not per-service): cross-service helpers only — `Fakers` (seeded),
  `FixedTimeProvider`, `InMemoryDb.Create()`. Service-specific `TestFixtureBase`/entity builders stay in
  their own test project (they reference that service's code). Never reference one test project from another.
- **Folders mirror the source** area; one test class per production class.
- **No `<Svc>.Domain.UnitTests` project** unless a domain type gains real behavior — record persistence-only
  domains as a gap, don't scaffold an empty project.

---

## Mandatory rules

### 1. Central Package Management (no inline versions)
Versions come from `tests/back-end unit/Directory.Packages.props`; shared MSBuild from `Directory.Build.props`.
A test `.csproj` lists `<PackageReference Include="..." />` with **no `Version`** (an inline Version with CPM
on is **NU1008**, an error). New package → add a `PackageVersion` centrally.
- **FluentAssertions pinned `7.2.0`** — never 8.x (commercial license).
- **Moq** is the repo mocking library — no NSubstitute/FakeItEasy.
- `Bogus` (seeded fakes) available via `App.TestCommon`; `Microsoft.EntityFrameworkCore.InMemory` pinned for
  `InMemoryDb`. If the project has no FluentValidation validators, don't add FluentValidation/`FluentValidation.TestHelper`.
- `Microsoft.Extensions.*` / EF Core / Npgsql pins must **match or exceed** what `src/` pins (a lower direct
  pin than the transitive requirement is **NU1605**, an error).

### 2. Stack, target `net10.0`
xUnit (runner) · FluentAssertions 7.2.0 · Moq · Bogus (seeded) · EF Core InMemory (only when a mocked repo
can't express the behavior) · coverlet on each test project.

### 3. Naming — `MethodName_Should_ExpectedBehavior_When_StateUnderTest`
AAA layout; one behavior per test; `[Theory]` for parameterized cases. e.g.
`EditOrder_Should_Throw_When_ChangeExceedsAgentCap`, `DeleteAsync_Should_ReturnFalse_When_WrongTenant`.
This is the **backend** convention — do NOT switch to the automation suites' `Given_When_Then`.

### 4. Hermetic isolation
No live SQL/Postgres, no message broker, no network, no cloud, no running app. Mock a service's repositories
and seams (`IUserRepository`, `IOrderRepository`, `IUnitOfWork`, `ICurrentUserService`,
`IFileStorageService`, notifiers, …) with Moq via the per-project `TestFixtureBase`. Reach for
`App.TestCommon.InMemoryDb.Create()` **only** when a Moq'd repository genuinely cannot express the behavior
(EF query shaping, change-tracker). **Provider caveat:** EF InMemory is not relational — it throws on
`ExecuteUpdateAsync`/`ExecuteDeleteAsync` and enforces no constraints; for those paths use SQLite in-memory.
(Note: if the project forbids raw SQL in app code, tests are EF/LINQ only too.)

### 5. Deterministic data
Build production entities/DTOs/requests via the per-project `Builders/*Builder.cs` or `App.TestCommon`
helpers backed by seeded `Fakers` — not hand-rolled inline where a builder exists. Only the **system under
test** and framework/stdlib types (`Mock<>`, `Guid`, `List<>`, `CancellationToken`, `byte[]`, …) are
`new`'d inline. **No clock/ordering/unseeded-randomness assertions:** `Fakers` sets `Randomizer.Seed` in a
static ctor; inject time via `FixedTimeProvider` (never `DateTime.UtcNow` in a test); honor the project
rule of non-nullable Guid/DateTime sentinels (`Guid.Empty`/`AuditableEntity.UnsetDate`) when building entities.

### 6. Mirror source & one class per production class
Folders mirror the service's areas; each `*Tests.cs` targets one production class. Each test project has a
`GlobalUsings.cs` (`global using Xunit;` + `global using FluentAssertions;`). Use **no** xUnit state fixtures
(`IClassFixture`/`ICollectionFixture`) — the shared layer is `App.TestCommon` (factories, not mutable
instances); a private `Build(...)` helper per test class keeps each Arrange to the one thing it varies.

### 7. No production edits; `InternalsVisibleTo` for internal types
**Never** modify `src/` (or the frontend) to make a test pass. To reach an `internal` type, add
`<InternalsVisibleTo Include="App.Service.<Svc>.UnitTests" />` to the **source** csproj — never widen to `public`.

### 8. Documented gaps — never silently skip
Code that can't be hermetically unit-tested (composition/DI, live HTTP, anemic domains, and any
environment constraint — e.g. an OS policy that blocks *running* a freshly-built unsigned service
assembly locally, forcing those tests into CI) goes under **Documented gaps** in
`tests/back-end unit/README.md` with its reason. `[Skip]`/`[Fact(Skip=…)]` is not coverage.

### 9. Reciprocal coverage
When a covered service/domain class is added/changed/renamed/removed, add or update the matching unit test in
the **same change**. (This is the standing project rule: tests + docs with every change.)

### 10. Green + zero new warnings
The affected project(s) build and run green with zero new warnings from your code. Where an OS policy blocks
running some freshly-built service assemblies locally (see rule 8), those projects compile locally but *run*
in CI. Compile-clean (`dotnet build App.sln … error CS` grep) + a green run of the locally-runnable
project(s) is the local bar.

---

## Events — publishers and handlers (mandatory for event code)

- **Publishers:** inject `RecordingEventPublisher` (`App.TestCommon`) as the `IEventPublisher` and assert what was
  staged: `Events.Should().HaveStagedOnly<OrderPlacedV1>(TenantId)` (and the negative: nothing staged when the
  write is refused or a no-op). A change that should publish and doesn't is a bug the integration suite won't localise.
- **Handlers (`IEventHandler<T>`):** cover the happy path, **the same message twice**
  (`EventDelivery.DeliverTwiceAsync`; the inbox dedupes by message id, but test the handler's own idempotency too), **a
  second, different message for the same aggregate**, **an older event after a newer one** (stale; skipped by as-of),
  and the tenant it runs under. A handler that erases personal data also gets the "late event after erasure" case.
- **Broadcast handlers** (cache eviction): assert the eviction; they're best effort, so don't test retries.
- Contract records live in `App.Shared.Events`; their snapshot and catalog tests are in `App.Infrastructure.UnitTests`.
  The architecture guards (`Architecture/`) are unit tests too: run them after any project-reference or HTTP-client change.

## The coverage bar per production class (service methods)

A suite is not done until it clears this, or the miss is named with a reason.

**Service method** (e.g. `SupportService.EditOrderAsync`, `AccountDeletionService.DeleteAsync`,
`LocationService.PushLocationAsync`) — happy path with the **real outcome** asserted; every guard/
early-return branch; not-found (returns null / false); conflict/duplicate; **permission or tenant refusal**
(capability `Require`, `TenantId` mismatch — the app is multi-tenant, this matters); the transaction/`IUnitOfWork`
path where one exists; each side effect verified `Times.Once` (repo `Add`/`Update`, `SaveChangesAsync`,
notifier push, audit write); and **on the failure path, the mutation/`SaveChanges`/notify verified
`Times.Never`** — a method that returns a failure but still persisted is a data-corruption bug no positive
test catches. Best-effort side effects (e.g. a swallowed realtime push) → assert the primary path still succeeds.

**Domain entity / value object** (only where it has behavior) — invariant enforced at construction; each legal
transition; each illegal transition refused; equality + `GetHashCode` for value objects.

**Negative balance:** negatives should be the **majority** — most branches in a service method are failure
branches. Walk: boundary values · null/empty/whitespace · not-found · conflict/duplicate · wrong tenant ·
capability denied · dependency throws · empty/single/many collections.

## Layer boundaries — don't re-prove elsewhere's job
Business rule/guard/branch/calculation, tenant/capability decisions, side-effect verification, mapping shape →
**backend unit** (here). Route binds / HTTP status / 401·403 / wire contract / row actually persisted →
**integration** (`api-testing`, `tests/integration`). Anything rendered → **functional** (`functional-testing`,
`tests/functional`). If you can't state what a test proves that a lower layer already proved, delete it.

## What does not count as coverage
Tautologies (asserting a mock returns what it was set up to return) · implementation assertions (private call
order instead of the business outcome) · multi-behavior tests (assert one behavior per test) · order-dependent
or shared-mutable-state tests · time/race-dependent tests · guessed assertions for undecided behavior (that's a
documented gap).

---

## Recipes

### A — add a test to an existing suite
Open the production service/method; note its constructor deps (repos, `ICurrentUserService`, `IUnitOfWork`,
notifiers), the request/response types, and **every branch**. Open/create the mirroring `*Tests.cs`; use the
project's `Build(...)` helper + `Mock<T>` for deps + `Builders`/`App.TestCommon.Fakers` for entities +
`FixedTimeProvider` for time. Cover the happy outcome, each guard/not-found/tenant/capability path, each side
effect, **and the negative side-effect** (nothing persisted/notified on failure). AAA + the naming rule.

### B — stand up tests for an untested service (e.g. Billing, Notifications)
Create `tests/back-end unit/App.Service.<Svc>.UnitTests` (CPM: bare refs; `IsTestProject=true`;
`GlobalUsings.cs`; ProjectReference to the service + `App.TestCommon`). Add a per-project `TestFixtureBase`
that builds the service with mocked repos/seams (mirror an existing service's unit-test project). Cover each
service method to the bar. Register in `App.sln`; add the row to the README coverage matrix.

### C — extend `App.TestCommon`
Add cross-service helpers only (a new seeded `Faker`, a shared fake). Service-specific fixtures/builders stay
in their test project. Keep helpers `public` (they cross the assembly boundary).

---

## Pre-merge checklist
- [ ] No inline `Version=` in any `tests/back-end unit` csproj; new packages pinned centrally; FluentAssertions still `7.2.0`.
- [ ] Names `MethodName_Should_ExpectedBehavior_When_StateUnderTest`; AAA; one behavior per test.
- [ ] Hermetic — Moq / `App.TestCommon` only; no live SQL/broker/network; no `Thread.Sleep`.
- [ ] Deterministic — seeded `Fakers`; `FixedTimeProvider` (no `DateTime.UtcNow`); sentinel Guid/DateTime where entities need them.
- [ ] No `IClassFixture`/`ICollectionFixture`.
- [ ] Every service-method test file has the **negative side-effect** test (nothing saved/notified on the failure path) where the method mutates.
- [ ] Tenant + capability refusal paths covered for support/admin-gated methods.
- [ ] No `src/`/frontend edits; internal access via `InternalsVisibleTo` on the source csproj only.
- [ ] Reciprocal: covered-layer production changes have matching test changes here.
- [ ] Nothing that belongs at integration/functional is re-proved here; no tautologies/implementation/multi-behavior tests.
- [ ] Untestable code is under **Documented gaps** in the README; nothing silently skipped.
- [ ] Affected project(s) compile clean; the locally-runnable project(s) run green; new projects registered in `App.sln`; README matrix updated.

---

## §11 Running the tests (incl. Replit / headless container)
Hermetic — runs anywhere with the SDK (no network/DB/browser/secrets); the right suite to run first.
```bash
cd <repo-root>
dotnet test "tests/back-end unit/App.Service.Billing.UnitTests/App.Service.Billing.UnitTests.csproj" -tl:off
dotnet test <proj> --filter "FullyQualifiedName~SupportServiceTests" -tl:off
dotnet test <proj> --collect:"XPlat Code Coverage" -tl:off
```
**Environment note:** if an OS policy (e.g. Windows **Application Control**) blocks *running* a freshly-built
unsigned service assembly locally — surfacing as `FileLoadException 0x800711C7` — those projects **COMPILE and
run in CI** but can't *run* locally. Verify those via `dotnet build App.sln … error CS` (compile) rather than
`dotnet test` locally.
**Memory-constrained agent:** a parallel MSBuild can OOM (surfaces as `InvalidCastException`/`SIGABRT`, not
"out of memory"). Build one project at a time: `dotnet build <proj> --no-restore --no-dependencies -m:1 -nodeReuse:false -p:UseSharedCompilation=false`.

**Capture output reliably** (the .NET logger swallows inline `echo $?`):
`(dotnet test <proj> --no-build -tl:off > /tmp/utest.log 2>&1; echo "RC=$?" >> /tmp/utest.log); tail -40 /tmp/utest.log`.

### Troubleshooting
| Symptom | Cause / fix |
|---|---|
| `IQueryable doesn't implement IAsyncEnumerable` | Handler runs EF async over `List.AsQueryable()`. Use `MockQueryable.Moq` `.BuildMock()` (pinned centrally) or `InMemoryDb`. |
| `ExecuteDelete/Update not supported by the in-memory store` | EF InMemory isn't relational — switch that test to SQLite in-memory. |
| `MissingMethodException` on a production library type | Test project resolved a different version than `src`; align the central pin. |
| `FileLoadException … 0x800711C7` on `dotnet test` | An OS policy (e.g. Windows Application Control) blocks the unsigned service assembly — run those tests in CI; compile-verify locally. |
| A test passes alone but fails in a full run | Shared mutable state (a static, a shared `Faker`, an `IClassFixture`). |

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 ai-agents →

Comments

Loading comments…

Newsletter

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