# Write Unit Tests for a .NET App

Yes. An agent finds the handlers and domain classes a .NET solution leaves untested, writes NUnit tests in the style already there, runs them and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/write-unit-tests/dotnet/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts with what the solution already uses, so the new tests look like the old ones. In a .NET solution like jasontaylordev/CleanArchitecture, `Directory.Packages.props` pins the test stack in one place: `nunit` 5.0.0 with `NUnit3TestAdapter`, `Moq` 4.21.0, `Shouldly` 4.3.0 and `coverlet.collector`. `Directory.Build.props` sets `net10.0`, `Nullable` and `TreatWarningsAsErrors`, so a test that leaves one nullable warning does not compile. Two projects hold unit tests. `tests/Application.UnitTests` has three files: `RequestLoggerTests`, which builds `LoggingBehaviour` from Moq doubles of `ILogger`, `IUser` and `IIdentityService`, `ValidationExceptionTests` and `MappingTests`. `tests/Domain.UnitTests` has one, `ColourTests`. The other test projects are a different kind: `Application.FunctionalTests` starts `TestAppHost` through Aspire and resets a real database with Respawn, and `Web.AcceptanceTests` drives a browser with Playwright and Reqnroll.

Then it lists what no unit test reaches. Under `src/Application/Common/Behaviours` there are five MediatR pipeline behaviours and only the logging one is tested: `AuthorizationBehaviour`, `ValidationBehaviour`, `UnhandledExceptionBehaviour` and `PerformanceBehaviour` have none. Neither do the `Result` model, `CreateTodoItemCommandValidator` and `UpdateTodoItemCommandValidator`, or `LogTodoItemCompleted`. In `src/Domain`, the `Done` setter on `TodoItem` adds a `TodoItemCompletedEvent` only when the value goes from false to true, `BaseEntity` keeps, removes and clears domain events, and `ValueObject` defines equality, a hash code and both operators; `ColourTests` touches the operators once and nothing else.

The tests follow from the branches in that code. For `AuthorizationBehaviour` the agent declares small request records in the test file, one with no attribute, one with `[Authorize]`, one with `Roles = "Administrator,Auditor"` and one with a `Policy`, and writes a case per outcome: no attribute calls `next` without reading the user, a null `IUser.Id` throws `UnauthorizedAccessException`, a user with neither role throws `ForbiddenAccessException`, the second role in the comma-separated list is enough, and a policy that `IIdentityService.AuthorizeAsync` refuses throws while one it accepts reaches `next` exactly once. `ValidationBehaviour` gets a pass-through case with no validators and a case where two failing validators produce one `ValidationException` whose `Errors` dictionary groups messages by property. `UnhandledExceptionBehaviour` must rethrow the same exception instance and log once at error level. `TodoItem` gets three cases: completing raises one event, completing twice still leaves one, and setting `Done` back to false raises none.

Two things it deliberately does not unit test, and says so. The two todo list validators check a unique title with `AnyAsync` on `IApplicationDbContext.TodoLists`, and the repository's ADR-001 states that data access is tested against a real database, which `CreateTodoListTests` in the functional project already does. `PerformanceBehaviour` reads a `Stopwatch` it creates itself and warns past 500 milliseconds, so the agent covers the fast path, where nothing is logged and `GetUserNameAsync` is never called, and reports that the slow path needs a clock seam instead of putting a sleep in the suite. It installs the SDK that `global.json` pins, runs `dotnet test` on the two unit projects with coverage collected before and after, then inverts the role check once to show a test going red and restores it.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Write unit tests for the untested code in this .NET solution. Read global.json, Directory.Build.props, Directory.Packages.props, docs/decisions, the two unit test projects under tests/ and everything under src/Application/Common and src/Domain first. Use the test stack already pinned (NUnit, Moq, Shouldly) and add no package. In tests/Application.UnitTests add tests for AuthorizationBehaviour (no attribute, unauthenticated user, missing role, one matching role in a comma-separated list, refused and accepted policy), ValidationBehaviour (no validators, failures grouped by property in ValidationException), UnhandledExceptionBehaviour (rethrows the same exception, logs once), the fast path of PerformanceBehaviour, Result, and the validators that need no database. In tests/Domain.UnitTests add tests for TodoItem.Done and its completed event, BaseEntity's domain events and ValueObject equality, hash code and operators. Do not mock the DbContext and do not change any file under src; list anything that needs a seam instead. Run dotnet test on the two unit test projects with coverage collected before and after, break AuthorizationBehaviour's role check once to show a failing test, restore it, and open a pull request with the commands and their output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request adds test files only: under `tests/Application.UnitTests`, `AuthorizationBehaviourTests`, `ValidationBehaviourTests`, `UnhandledExceptionBehaviourTests` and `PerformanceBehaviourTests` beside the existing `RequestLoggerTests`, a `ResultTests` under `Common/Models` and validator tests under `TodoItems`; under `tests/Domain.UnitTests`, `TodoItemTests`, `BaseEntityTests` and `ValueObjectTests`. Nothing under `src` changes and `Directory.Packages.props` is untouched, because every package the tests need is already pinned there. The description quotes the `dotnet test` output for both projects, line coverage for the Application and Domain assemblies before and after, the red run with the role check inverted, and a short list of what was left alone: the uniqueness rule that belongs to the functional tests and the slow path of `PerformanceBehaviour`.

A reviewer checks that each test asserts what a caller would observe, an exception type or a call to `next`, not the order of private statements, that the request records used for authorization live in the test assembly and not in `src/Application`, and that the solution still builds with warnings as errors. Once merged, `.github/workflows/build.yml` runs them on every pull request, since its last step is `dotnet test` on the whole solution.

## Run it on every merged pull request

An automation in the Project that holds the repository takes a `github` trigger on `pull_request.closed.merged`. The trigger adds the merged pull request after the saved prompt and fills nothing in, so the prompt says what to do with it: read the files that pull request changed under `src/Application` and `src/Domain`, find the handlers, validators and entities with no unit test, write them in the existing style and open a pull request. Set its max runs per hour to the pace the team merges at, so a release day queues runs instead of starting them all.

To start it from a server instead, send this body with an API key when your own pipeline finishes a merge, with a `request_id` that is a UUID v5 of the merge commit SHA so a retried delivery returns the run it already started. Give the key a webhook URL and `run.completed` arrives with the `session_url`; reading that session names the new pull request.

## Why run it on Rush?

Tests for pipeline behaviours are only worth reviewing once they have compiled under `TreatWarningsAsErrors` and run. In its own sandbox the agent installs the SDK the solution pins, restores from the central package file, runs both unit projects, collects coverage twice and breaks the code once on purpose, and the full output of each command stays in the run's record. Nobody's machine needs the right SDK band, and a developer's working branch is never touched.

The run also respects where this solution draws its lines. It reads the ADRs before writing, keeps database behaviour in the functional tests where the repository put it, and names the one class that cannot be tested without a seam instead of quietly editing it. A team with several services built from the same template starts one run per repository and gets one pull request each, written against that service's own handlers.

## Frequently asked questions

### Will it use xUnit or NUnit?

Whatever the solution already uses. Here that is NUnit with Shouldly assertions and Moq doubles, all pinned in `Directory.Packages.props`, so the run adds no package. On a solution that uses xUnit the same prompt produces xUnit tests, because the agent reads the existing test projects before writing.

### Why does it run only the unit test projects?

The functional tests start an Aspire test host and a database, and the acceptance tests need Playwright's browsers installed. Unit tests need neither and finish quickly, so the run proves them alone. Ask in a follow-up to the same session and the agent runs the whole solution the way `build.yml` does.

### Does it mock the DbContext to test handlers?

No. The handlers call `FindAsync`, `AnyAsync` and `SaveChangesAsync` on `IApplicationDbContext`, and the repository's own decision record says that behaviour is tested against a real provider. The agent tests the logic that has no database in it and leaves handlers to the functional project.

### Will it change production code to make it testable?

Not in this run. Where a class cannot be tested as written, such as a behaviour that owns its `Stopwatch`, the pull request describes the smallest seam that would fix it. A follow-up message can ask for that change as a separate commit.

## More .NET jobs

- [Add API Versioning to ASP.NET Core Minimal API Endpoints](https://getrush.ai/run/add-api-versioning/dotnet/)
- [Add Architecture Tests to a .NET Clean Architecture Solution](https://getrush.ai/run/add-architecture-tests/dotnet/)
- [Add Code Coverage to CI for a .NET Solution](https://getrush.ai/run/add-coverage-to-ci/dotnet/)

## The same job on other stacks

- [Write Unit Tests for an Echo API](https://getrush.ai/run/write-unit-tests/echo/)
- [Write Unit Tests for an Elixir Project](https://getrush.ai/run/write-unit-tests/elixir/)
- [Write Unit Tests for a Fiber v3 App](https://getrush.ai/run/write-unit-tests/fiber/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
