# Write bUnit Tests for a Blazor Web App

Yes. An agent adds a bUnit test project to your Blazor Web App, renders the pages against an in-memory SQLite context, runs dotnet test and opens a PR.

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

## What the agent does

The agent reads the app's composition before writing a single test, because a Blazor page is only testable once its injected services can be replaced. In an app like `10.0/BlazorWebAppMovies` in dotnet/blazor-samples, the `.csproj` targets `net10.0` on the `Microsoft.NET.Sdk.Web` SDK with the QuickGrid EF Core adapter, EF Core for SQL Server and the EF tools; `Program.cs` registers `AddDbContextFactory<BlazorWebAppMoviesContext>` over `UseSqlServer` with a LocalDB connection string from `appsettings.json`, `AddQuickGridEntityFrameworkAdapter()`, Razor components with interactive server rendering, and seeds the database from `Data/SeedData.cs` at startup. `Models/Movie.cs` carries the data annotations: a required title of 3 to 60 characters, a genre regex, a price range, a rating restricted to `G`, `PG`, `PG-13`, `R` and `NC-17`. `Components/Pages/MoviePages/Index.razor` injects the context factory, filters `context.Movie` by a `titleFilter` bound to a search input with `@bind:event="oninput"`, and renders a `QuickGrid` with a `PaginationState` of five items per page; `Details.razor` reads `Id` with `[SupplyParameterFromQuery]` and calls `NavigationManager.NotFound()` for a missing row; `Create.razor` is an `EditForm` with `DataAnnotationsValidator`, `[SupplyParameterFromForm]` and `OnValidSubmit`; `Counter.razor` is the template counter. `BlazorWebAppMovies.slnx` lists the one project and the repository has no test project at all.

The test project goes beside the app as `BlazorWebAppMovies.Tests`, created the way bUnit's own template does it: the `Microsoft.NET.Sdk.Razor` SDK so `.razor` test files compile, `net10.0`, the `bunit`, `xunit`, `xunit.runner.visualstudio`, `Microsoft.NET.Test.Sdk` and `coverlet.collector` packages, a `ProjectReference` to the app, and an entry in `BlazorWebAppMovies.slnx`. Because the app's context factory points at SQL Server, the test project adds `Microsoft.EntityFrameworkCore.Sqlite` and a small fixture that opens one `DataSource=:memory:` connection, calls `EnsureCreated`, and registers `AddDbContextFactory<BlazorWebAppMoviesContext>` over `UseSqlite` on that connection plus `AddQuickGridEntityFrameworkAdapter()` on bUnit's service collection, so the pages render against real EF Core queries without LocalDB.

The tests follow the pages. `CounterTests` renders `Counter`, clicks the button and asserts the `role="status"` paragraph. `MovieIndexTests` inserts seven movies through the fixture, renders `Index`, asserts five table rows on the first page and a paginator, types into the search input with `Input` and asserts the rows shrink to the matching titles, and checks that each row's edit, details and delete links carry the movie id in their query string. `MovieDetailsTests` navigates bUnit's navigation manager to `/movies/details?id=1` before rendering so `[SupplyParameterFromQuery]` resolves, and asserts the definition list shows that movie's title and rating. `MovieCreateTests` renders `Create`, submits the form with an empty title and a rating outside the regex, and asserts the two validation messages, then fills valid values and asserts the row exists in the context after `OnValidSubmit`. Where a Blazor feature is not supported by bUnit's test navigation manager, such as `NotFound()`, the agent checks before writing the case and lists it in the pull request instead of asserting around it.

The agent installs the .NET 10 SDK in its sandbox, runs `dotnet build` on the solution and `dotnet test 10.0/BlazorWebAppMovies.Tests`, and reads every failure itself before the pull request exists. Because the repository's `.editorconfig` asks for CRLF line endings and four-space indentation in `.cs` and `.razor` files, the new files follow it. A small `.github/workflows/blazor-tests.yml` runs `dotnet test` on `ubuntu-latest` with `actions/setup-dotnet` on `10.0.x`, pinned by commit SHA like the repository's existing `static.yml`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Write bUnit tests for the Blazor Web App in 10.0/BlazorWebAppMovies. Read BlazorWebAppMovies.csproj, BlazorWebAppMovies.slnx, Program.cs, appsettings.json, Models/Movie.cs, Data/BlazorWebAppMoviesContext.cs, Data/SeedData.cs, Components/_Imports.razor, Components/Routes.razor, Components/Pages/Counter.razor and every file under Components/Pages/MoviePages first, and keep the app's code unchanged. Create 10.0/BlazorWebAppMovies.Tests on the Microsoft.NET.Sdk.Razor SDK targeting net10.0 with bunit, xunit, xunit.runner.visualstudio, Microsoft.NET.Test.Sdk, coverlet.collector and Microsoft.EntityFrameworkCore.Sqlite, a ProjectReference to the app, and add it to the slnx. Write a fixture that opens an in-memory SQLite connection, creates the schema and registers AddDbContextFactory over UseSqlite and AddQuickGridEntityFrameworkAdapter on the test services. Write CounterTests, MovieIndexTests covering the five-row first page, the title filter and the row links, MovieDetailsTests navigating to /movies/details with an id before rendering, and MovieCreateTests covering the validation messages for an empty title and an invalid rating and a valid submit. Check which navigation features bUnit supports before asserting on NotFound and list any case you skip. Follow .editorconfig. Add .github/workflows/blazor-tests.yml running dotnet test with actions/setup-dotnet on 10.0.x, pinned by SHA like static.yml. Run dotnet build and dotnet test until they pass and open a pull request that lists each test and what it asserts.",
  "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

What comes back is a pull request that adds `10.0/BlazorWebAppMovies.Tests` with its `.csproj`, the SQLite fixture and four test classes, adds the project to `BlazorWebAppMovies.slnx`, and adds `.github/workflows/blazor-tests.yml`. The app's own files are untouched. The description lists each test and the behaviour it pins down, names the package versions that were restored, and says which Blazor feature, if any, bUnit could not drive so the gap is visible.

The run's record keeps the SDK install, `dotnet build` and the `dotnet test` output with each test's name and result, so a reviewer reads the pass list rather than installing .NET 10 and LocalDB to find out.

Before merging, a reviewer decides whether the SQLite fixture should become a shared test base for the other sample apps in the repository, and whether the workflow should run on `windows-2022` as the repository's `snippets5000.yml` does, since the tests themselves need neither Windows nor SQL Server.

## Run it on every night

In the console, add an automation to the Project with this prompt and a `schedule` trigger, a `cron` of `0 2 * * *` and your `timezone`. Each night one run reads which components changed since the last run, writes bUnit tests for the pages and components that have none, runs `dotnet test` and opens one pull request on its own branch. A run whose new tests cannot be made to pass ends `needs_review` rather than opening anything.

The same body sent to `POST /o/{org}/sessions` with the repository in `resources` starts one run by hand, for instance before a release. A `request_id` that is a UUID v5 of the release tag makes a retried call return that run instead of a second pull request.

## Why run it on Rush?

Component tests for an app that talks to SQL Server through a context factory need a sandbox where the .NET 10 SDK, a replacement database and the full `dotnet test` run can happen without touching anyone's machine or a LocalDB instance. The agent builds that fixture, runs the tests after each file it writes, and reads the failures itself, so a page that renders differently under bUnit than in the browser is understood before anyone reviews it.

Because the `dotnet test` output stays with the record, the pull request can say exactly which page behaviours are now pinned down and which one bUnit could not reach, with the run to show for it, instead of asking a reviewer to trust that the suite was run.

## Frequently asked questions

### Do the tests need SQL Server or LocalDB?

No. The test fixture registers the same `IDbContextFactory<BlazorWebAppMoviesContext>` the pages inject, but over an in-memory SQLite connection kept open for the test's lifetime. The pages' EF Core queries, including the QuickGrid adapter's paging, run against it unchanged.

### Can bUnit test pages that use interactive server rendering?

Yes. bUnit renders the component tree in-process and dispatches events such as clicks and input directly, so `@rendermode InteractiveServer` on `Index.razor` and `Counter.razor` does not matter to the test. Streaming and enhanced form posts are server features it does not simulate, which is why the create test calls `OnValidSubmit` through the form rather than through an HTTP post.

### Why xUnit?

It is the default of bUnit's own project template and of `dotnet new`. The same packages exist for NUnit and MSTest, and the pull request names the two lines in the `.csproj` to change for either.

### Does the test project change how the app builds?

The app's `.csproj` is untouched. The test project references it and is added to the `.slnx`, so `dotnet build` at the solution level now builds both, and `dotnet test` finds the one test project.

## More Blazor jobs

- [Write Playwright Tests for a Blazor Web App](https://getrush.ai/run/write-playwright-tests/blazor/)
- [Add CSV Export to a Blazor Web App](https://getrush.ai/run/add-csv-export/blazor/)
- [Add Dark Mode to a Blazor Web App](https://getrush.ai/run/add-dark-mode/blazor/)

## More jobs like this: Write the missing tests

- [Write Tests for an AWS CDK App](https://getrush.ai/run/write-cdk-assertion-tests/aws-cdk/)
- [Write Tests for a Go CLI](https://getrush.ai/run/write-cli-tests/go-cli/)
- [Write Integration Tests for a Rust CLI](https://getrush.ai/run/write-cli-tests/rust-cli/)

## 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/)
