Claude Code hooks for .NET: Make Claude build and run your unit tests
Claude Code said it had completed its tasks in my .NET app. I hit build, and it didn't even compile. It's not just the build either. Claude Code has changed code that had unit tests and never run them, then told me the job was done. I'll show you how to add a hook that stops Claude Code finishing until your .NET app builds and the unit tests pass.
Claude Code doesn't always build or run the tests
You can add "build and run the unit tests" to every prompt, but there's no guarantee that Claude Code will actually do it.
It's not just me. A developer building a .NET Web API found Claude Code had been telling them for hours that it was running the tests. It wasn't. It was showing them old results, and only admitted it when it was pushed.
Even Anthropic's own guide for Sonnet 5.5 says that at low effort, it sometimes reports a change as done without running a check.
Adding a rule to CLAUDE.md doesn't solve it either. Anthropic's best practices say that a rule like "always typecheck before you finish" works most of the time, but not every time.
However, there is a way to make Claude Code run the check every single time, without you even asking.
Breaking the build
To simulate how Claude Code can behave, I deliberately broke an application by removing a semicolon after _products.Add(product) in ProductService.cs.
// ProductService.cs
public class ProductService : IProductService
{
...
public async Task<GetProductDto> CreateProductAsync(
CreateProductDto createProduct,
CancellationToken cancellationToken)
{
...
_products.Add(product) // Missing semicolon
return product;
}
}
}This is a file that Claude Code has no reason to open as I then asked it to add a new rule to CreateProductDtoValidator, so that the product name has to be at least three characters long.
// CreateProductDtoValidator.cs
public class CreateProductDtoValidator : AbstractValidator<CreateProductDto>
{
public CreateProductDtoValidator()
{
RuleFor(p => p.Name)
.NotEmpty()
.MaximumLength(100);
...
}
}This is the prompt I gave to Claude Code.
Can you make a single change in
CreateProductDtoValidatorso product names must be at least 3 characters
Claude Code found the validator and added .MinimumLength(3) to the Name rule, so names now have to be between 3 and 100 characters long.
// CreateProductDtoValidator.cs
public class CreateProductDtoValidator : AbstractValidator<CreateProductDto>
{
public CreateProductDtoValidator()
{
RuleFor(p => p.Name)
.NotEmpty()
.MinimumLength(3)
.MaximumLength(100);
...
}
}The changes were complete, but it didn't build the project. It mentioned that it hadn't built the project or run the tests. But that could easily be missed. It isn't until you next build the project that you realise it's failing.
Get notified of new content
Join other .NET developers improving their skills and knowledge.
What are Claude Code hooks?
Claude Code Hooks are commands that Claude Code runs at fixed points in its lifecycle, such as before it uses a tool or when it finishes responding. Claude Code runs them itself, so the agent doesn't have to remember an instruction.
The Stop hook runs when Claude Code finishes responding. If the hook exits with code 2, Claude Code is prevented from stopping, and whatever the hook writes to stderr is sent back to Claude as the reason.
Adding a Stop hook
You add a hook to the settings.json file in the .claude folder at the root of your solution.
This Stop hook runs a command that builds the solution and runs the unit tests.
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "dotnet build RoundTheCode.HooksProductsApi.slnx --nologo -v q 1>&2 && dotnet test RoundTheCode.HooksProductsApi.slnx --no-build --nologo 1>&2 || exit 2"
}
]
}
]
}
}How the command works
Each part of the command has its own job.
dotnet build RoundTheCode.HooksProductsApi.slnx: The solution file is named. Without it,dotnetstops with an error when the folder has more than one project or solution file.--nologo -v q: The build runs quietly, so only errors and warnings come through.&& dotnet test --no-build: The tests only run if the build worked, and the solution isn't built twice.1>&2: The output is sent tostderr, because that's what Claude Code feeds back to Claude.|| exit 2: If anything fails, the command exits with code 2, so Claude Code can't finish.
To check that the hook has loaded, start Claude Code and run the /hooks command. The Stop hook appears in the list.
Running the prompt with the Stop hook
With the hook in place, I ran the same prompt again, with the semicolon still missing from ProductService.cs.
Claude Code made the same change to the validator. But when it tried to finish, the Stop hook built the solution and the build failed. Because the build failed, the tests didn't run, and the compiler error went straight back to Claude.
Claude Code read ProductService.cs and checked the changes in Git. It found that the missing semicolon wasn't caused by its own change. It was a change that I had made before the session started.
As I had only asked for a single change, it asked me whether it should put the semicolon back. I told it to fix it.
Claude Code added the semicolon back in, and the hook ran again. This time, the build succeeded and all 12 tests passed. Only then was Claude Code allowed to finish, and it listed both changes it had made.
Using the Stop hook with failing unit tests
The next test was to see how the hook works when a unit test fails.
The demo project
The demo project is an ASP.NET Core Web API that uses Minimal APIs. Sending a POST request to /api/products creates a product with a name and a price.
When a product is created, it's validated by CreateProductDtoValidator, which makes sure that the price is greater than zero.
// CreateProductDtoValidator.cs
public class CreateProductDtoValidator : AbstractValidator<CreateProductDto>
{
public CreateProductDtoValidator()
{
...
RuleFor(p => p.Price)
.GreaterThan(0);
}
}The ApplicationTests project has a unit test called CreateProductAsync_PriceIsZero_ThrowsValidationException that confirms this. If the price is zero, a ValidationException is thrown.
// ProductServiceTests.cs
public class ProductServiceTests
{
...
[Fact]
public async Task CreateProductAsync_PriceIsZero_ThrowsValidationException()
{
var createProduct = new CreateProductDto
{
Name = "Mouse",
Price = 0m
};
var act = await Assert.ThrowsAsync<ValidationException>(() =>
_productService.CreateProductAsync(
createProduct,
TestContext.Current.CancellationToken));
Assert.Contains(act.Errors, e => e.PropertyName == nameof(CreateProductDto.Price));
}
...
}Updating the unit test
I wanted to allow free products. I expected Claude Code to make the change to the validator and also update the unit test. This is the prompt I gave to Claude Code.
Can you make a single change in
CreateProductDtoValidatorwhere free products are allowed
Claude Code changed the price rule from .GreaterThan(0) to .GreaterThanOrEqualTo(0), so a price of zero passes validation and negative prices are still rejected.
It said that this would break the CreateProductAsync_PriceIsZero_ThrowsValidationException test. But as I had asked for a single change, it didn't run the tests or touch the test file.
Then the Stop hook ran. The build succeeded, but the test failed because no exception was thrown, and the test output went straight back to Claude.
Claude Code was blocked from finishing, so it updated the test to match the new rule. It renamed the test to CreateProductAsync_PriceIsZero_ReturnsCreatedProduct, and it now checks that a product with a price of zero is created and returned.
// ProductServiceTests.cs
public class ProductServiceTests
{
...
[Fact]
public async Task CreateProductAsync_PriceIsZero_ReturnsCreatedProduct()
{
var createProduct = new CreateProductDto
{
Name = "Mouse",
Price = 0m
};
var act = await _productService.CreateProductAsync(
createProduct,
TestContext.Current.CancellationToken);
Assert.Equal(new GetProductDto(4, "Mouse", 0m), act);
}
...
}The hook ran again and all 12 tests passed. Claude Code explained that it had made a second change to ProductServiceTests.cs to get past the hook.
Other hook types
The Stop hook isn't the only one. Two more that are useful in a .NET app are PreToolUse and PostToolUse. PreToolUse runs just before Claude Code uses a tool, such as editing a file, and PostToolUse runs after it has finished using it.
PreToolUse
This PreToolUse hook stops Claude Code writing EF Core migrations by hand. Add it inside hooks, next to Stop.
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"if": "Edit(**/Migrations/**)",
"command": "echo 'Do not write EF Core migrations by hand. Run dotnet ef migrations add instead.' 1>&2; exit 2"
}
]
}
]The matcher means it only runs when Claude Code edits or writes a file. The if narrows it down to any file in a Migrations folder, at any depth. An Edit rule covers the Write tool as well.
The message is written to stderr and the hook exits with code 2. The edit is blocked, and Claude Code is told to run dotnet ef migrations add instead.
I've seen AI write migrations by hand, and when you run them, they don't work. This hook makes sure it uses the EF Core migration tool. As dotnet ef writes the migration files itself, rather than through Claude Code's Edit or Write tools, the hook doesn't block the proper way of creating a migration.
PostToolUse
This PostToolUse hook runs dotnet format on every C# file that Claude Code edits.
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"if": "Edit(*.cs)",
"shell": "powershell",
"command": "$f = ([Console]::In.ReadToEnd() | ConvertFrom-Json).tool_input.file_path; dotnet format RoundTheCode.HooksProductsApi.slnx --include (Resolve-Path -Relative $f)"
}
]
}
]The if makes sure it only runs for .cs files. The command runs in PowerShell. Claude Code sends the hook input as JSON, and PowerShell reads the edited file from tool_input.file_path.
Claude Code passes the full path of the file, but the --include option in dotnet format expects a relative path. Resolve-Path -Relative converts it. With a full path, dotnet format exits successfully but formats nothing.
This means the code is formatted the way you want it, even when AI writes it.
This is the full settings.json file with all three hooks.
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"if": "Edit(**/Migrations/**)",
"command": "echo 'Do not write EF Core migrations by hand. Run dotnet ef migrations add instead.' 1>&2; exit 2"
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"if": "Edit(*.cs)",
"shell": "powershell",
"command": "$f = ([Console]::In.ReadToEnd() | ConvertFrom-Json).tool_input.file_path; dotnet format RoundTheCode.HooksProductsApi.slnx --include (Resolve-Path -Relative $f)"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "dotnet build RoundTheCode.HooksProductsApi.slnx --nologo -v q 1>&2 && dotnet test RoundTheCode.HooksProductsApi.slnx --no-build --nologo 1>&2 || exit 2"
}
]
}
]
}
}Watch the video
Watch the video where I show you how to add a Stop hook so Claude Code can't finish until your .NET app builds and the unit tests pass, and how the PreToolUse and PostToolUse hooks work.
Related tutorials
Let Claude Code write your skills in plan mode. Prompts and plans for two .NET skills that add an EF Core entity and a Minimal API endpoint without guessing.
Find out how AI is better than .NET developers at creating projects, writing unit tests, adding comments and debugging exceptions.