Covers the Arrange-Act-Assert structure, test naming conventions, the one-behaviour-per-test rule, and how they make xUnit test failures readable.
Arrange-Act-Assert (AAA) splits a test into three blocks: Arrange builds the object under test and its inputs, Act makes one call to the behaviour being tested, and Assert checks the result or the observable side effect.
I name tests after the behaviour, for example PlaceOrder_WhenStockIsZero_ReturnsOutOfStock, so the test runner's failure list reads like a specification. And each test checks one behaviour: it can have several asserts if they describe the same outcome, but it should fail for one reason only.
The trade-off: strict AAA and narrow tests mean more test methods, but each failure points straight at the broken rule instead of making you debug the test.
"Arrange-Act-Assert is just a shape for a test, but it is the shape that makes tests readable months later. In the Arrange block I build the system under test and everything it needs: inputs, fakes, a fixed clock. The Act block is one line, the single call whose behaviour I am specifying. The Assert block checks what that call produced: a return value, a state change, or a message sent to a collaborator. I separate the three with a blank line, and in xUnit I don't need comments for it.
Naming matters as much as structure, because the name is what you read in the CI report. I use
Method_Scenario_ExpectedResult, likeWithdraw_WhenBalanceIsInsufficient_ThrowsInsufficientFunds, or a plain sentence class per feature. If the name needs the word 'and', it is usually two tests. 'One behaviour per test' is not 'one Assert per test': checking that a returned order has status Confirmed and a total of 120 is fine, because both describe the same outcome. What I avoid is a test that places an order, then cancels it, then refunds it, and asserts all three, because when it fails you don't know which rule broke.The mistake I see is logic creeping into tests: loops over test cases, if statements, try/catch around the Act. A test with a branch is a test that can pass for the wrong reason. Repeated cases go into
[Theory]with[InlineData], and expected exceptions go throughAssert.Throws. A good test fails for exactly one reason and tells you that reason in its name."
| Block | Contains | Smell when it goes wrong |
|---|---|---|
| Arrange | Construct SUT, inputs, fakes, fixed TimeProvider |
30 lines of setup: extract a builder |
| Act | One call to the behaviour under test | Several calls: you are testing a workflow, split it |
| Assert | Return value, state change or interaction | Asserting things the Act didn't cause |
| Style | Example | When it fits |
|---|---|---|
Method_Scenario_Expected |
Withdraw_WhenOverdrawn_Throws |
Most service and domain tests |
| Sentence | Overdrawn_account_cannot_withdraw |
Behaviour-focused suites, nested classes per feature |
| Given/When/Then | Given_zero_stock_When_ordering_Then_rejected |
BDD-leaning teams |
Pick one per solution and enforce it in review; consistency matters more than which style.
| Fine | Not fine |
|---|---|
| Two asserts on one returned DTO | Asserting on results of three separate Act calls |
Assert.Multiple (xUnit v3) to report all failures of one outcome |
One test covering create, update and delete |
On a payments service with about 1,800 unit tests, renaming tests to the Method_Scenario_Expected style and splitting multi-behaviour tests cut the time to triage a red build from "open the test and debug it" to reading the failure list. The number of tests rose by roughly 15%, but the run time barely moved because each test stayed under a millisecond.
Checks whether the candidate writes tests that are readable and diagnosable, not just tests that pass.
Green flags
[Theory]/[InlineData] instead of loopsRed flags
Test1 or ShouldWorkTests are read far more often than they are written: in code review, when they fail in CI, and when someone changes behaviour. A fixed shape means the reader knows where to look:
[Arrange] build the world -> "given this situation"
[Act] poke it once -> "when this happens"
[Assert] check what changed -> "then I expect this"
AAA is the same idea as Given/When/Then from BDD. The value is not the comments, it is that the Act line is easy to find.
xUnit creates a new instance of the test class for every test method. The constructor is your per-test Arrange for shared setup, and IDisposable / IAsyncLifetime is teardown. That isolation is why shared mutable fields don't leak between tests in the same class, and why static fields do.
for each [Fact]/[Theory] row:
new TestClass() // constructor = common Arrange
await InitializeAsync() (IAsyncLifetime)
run method // Arrange-Act-Assert
await DisposeAsync() / Dispose()
A behaviour is one rule of the system: "an order with no stock is rejected". Checking that the result is a failure, that the error code is OutOfStock, and that nothing was saved are three asserts on one behaviour. Testing "reject" and "accept" in one method is two behaviours.
A plain xUnit assert throws an exception when it fails, so by default the test ends at the first failed assert and later mismatches stay hidden. Two ways to see every mismatch at once:
Assert.Multiple(...) (xUnit v3), which runs them all and reports every failure together;Assert.Equal(expected, actual); records give you value equality and the failure message shows both values.The test explorer and CI report show only names. A good name answers: what unit, under what condition, with what result. Compare:
Test1 -> tells nothing
PlaceOrder_Works -> what does 'works' mean?
PlaceOrder_WhenStockIsZero_ReturnsOutOfStock -> readable spec
When Arrange grows, the real problem is usually the design of the class under test (too many dependencies) or missing helpers. Fixes in order: a private factory method CreateSut(), a test data builder (new OrderBuilder().WithLines(2).Build()), then fixtures for expensive shared resources.
Narrow tests are cheap to run: pure unit tests in xUnit typically take well under a millisecond each, and xUnit runs test classes (collections) in parallel by default. Splitting one workflow test into four behaviour tests barely changes suite time; what slows suites down is I/O in Arrange, not the number of methods.
[Theory] with [InlineData]; compare the failure output.Method_Scenario_Expected and read the test explorer as if it were a spec.Assert.Multiple and then with one Assert.Equal on an expected record; break two fields and compare the output.A small domain rule and its xUnit tests, written in Arrange-Act-Assert with behaviour-style names.
#nullable enable
namespace Shop.Tests;
using Xunit;
// Code under test
public sealed record OrderResult(bool Accepted, string? Error);
public sealed class OrderService(IStock stock)
{
public OrderResult Place(string sku, int quantity)
{
if (quantity <= 0) return new(false, "InvalidQuantity");
return stock.Available(sku) >= quantity
? new(true, null)
: new(false, "OutOfStock");
}
}
public interface IStock { int Available(string sku); }
// A hand-written stub keeps Arrange obvious
file sealed class StubStock(int available) : IStock
{
public int Available(string sku) => available;
}
public sealed class OrderServiceTests
{
[Fact]
public void Place_WhenStockIsSufficient_AcceptsOrder()
{
// Arrange
var sut = new OrderService(new StubStock(available: 5));
// Act
var result = sut.Place("SKU-1", quantity: 2);
// Assert: two asserts, one behaviour
Assert.Equal(new OrderResult(true, null), result);
}
[Fact]
public void Place_WhenStockIsZero_ReturnsOutOfStock()
{
var sut = new OrderService(new StubStock(available: 0));
var result = sut.Place("SKU-1", quantity: 1);
Assert.False(result.Accepted);
Assert.Equal("OutOfStock", result.Error);
}
// Repeated cases go in a Theory, not a loop inside one test
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void Place_WhenQuantityIsNotPositive_ReturnsInvalidQuantity(int quantity)
{
var sut = new OrderService(new StubStock(available: 10));
var result = sut.Place("SKU-1", quantity);
Assert.Equal("InvalidQuantity", result.Error);
}
}
Test1, ShouldWork or after the method only. Why it is wrong: The CI report shows only names, so a failure tells you nothing. Instead: Name the scenario and the expected result.if statements inside a test. Why it is wrong: The test can pass for the wrong reason, and the failure doesn't say which case broke. Instead: Use [Theory] with [InlineData] or [MemberData].try/catch to check an exception. Why it is wrong: If no exception is thrown the test may still pass. Instead: Assert.Throws<T> or await Assert.ThrowsAsync<T>.AAA and naming are cheap discipline that pays off at scale: when a suite has thousands of tests, the only thing anyone reads during a red build is the name and the assert message. Consistent structure is also a team tool: reviewers can check a test in seconds, new joiners can read the suite as a specification, and whoever is on call can triage a failure without the author. I treat a long Arrange as design feedback (the class has too many dependencies), not as a reason to add a clever base class. Deep test inheritance hierarchies make AAA invisible because the Arrange lives three files away.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Plain AAA with blank lines | Default for unit tests | None | Never a bad default |
Private CreateSut() helper |
Same SUT setup across a class | Small indirection | When each test needs different wiring |
| Test data builder | Rich domain objects | A builder class per aggregate | Simple value inputs |
| Base test class | Truly shared infrastructure (e.g. a host) | Hidden setup, coupling | Hiding per-test Arrange |
To measure whether it works, watch time-to-triage on red builds and how often reviewers ask "what is this test checking?"; agree the naming convention in the team's testing guidelines so it is enforced in review rather than by taste.
A unit test checks one piece of behaviour in memory with no I/O: a pricing rule, a validator, a domain method. It runs in milliseconds and tells you exactly which logic broke. An integration test checks that real parts work together: the ASP.NET Core pipeline, routing, model binding, EF Core against a real SQL Server. It takes seconds and catches wiring, mapping and SQL mistakes that unit tests can't see. An end-to-end test drives the deployed system the way a user does, through a browser or the public API, and proves a whole journey works.
The trade-off: as you move from unit to E2E, each test gives more confidence that the real thing works but is slower, flakier and worse at saying where the problem is.
These are Gerard Meszaros's five test doubles:
I hand-roll a fake when the dependency holds state and many tests use it. Microsoft already ships two: FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) and FakeLogger (Microsoft.Extensions.Diagnostics.Testing). One small class replaces dozens of fragile mock setups. The trade-off is that a fake is code you maintain. Mocks cost nothing to write, but they break whenever the implementation changes.
Last updated 23 Nov 2026.