📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the Arrange-Act-Assert pattern? How do you name unit tests so a failure explains itself, and why should each test check one behaviour?

Covers the Arrange-Act-Assert structure, test naming conventions, the one-behaviour-per-test rule, and how they make xUnit test failures readable.

Beginner Theory Beginner arrange-act-assert test-naming test-readability testing unit-testing xunit

🎯 Key points

  • Arrange sets up inputs and collaborators, Act makes exactly one call, Assert checks the outcome
  • Name tests Method_Scenario_ExpectedResult or as a sentence so the failure message tells the story
  • One behaviour per test: several asserts are fine only when they all describe that same behaviour's outcome
  • Keep the Act line obvious; if Arrange is long, extract a builder or factory method
  • No logic (if, loops, try/catch) in tests: a test with branches needs its own test
  • Parameterise with [Theory] and [InlineData] instead of copy-pasting near-identical tests
  • A failing test should point to one reason without opening the debugger
  • Consistent structure and naming make a large suite maintainable by the whole team

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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, like Withdraw_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 through Assert.Throws. A good test fails for exactly one reason and tells you that reason in its name."


The three blocks

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

Naming styles

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.

One behaviour vs one assert

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate writes tests that are readable and diagnosable, not just tests that pass.

Green flags

  • Explains AAA with a clear single Act line
  • Distinguishes one behaviour per test from one assert per test
  • Uses [Theory]/[InlineData] instead of loops
  • Names tests so the failure list reads like a spec

Red flags

  • Logic or try/catch inside tests
  • Names like Test1 or ShouldWork
  • Workflow tests with several Act calls presented as unit tests

📚 Learn in depth

1. Why a fixed shape helps

Tests 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.

2. How xUnit runs a test

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()

3. One behaviour, many asserts

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:

  • wrap related asserts in Assert.Multiple(...) (xUnit v3), which runs them all and reports every failure together;
  • compare a whole expected record with Assert.Equal(expected, actual); records give you value equality and the failure message shows both values.

4. Names as documentation

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

5. Keeping Arrange small

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.

6. Scale: thousands of tests

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.

Try it yourself

  1. Take a test with a loop over cases and rewrite it as a [Theory] with [InlineData]; compare the failure output.
  2. Rename ten tests in an existing project to Method_Scenario_Expected and read the test explorer as if it were a spec.
  3. Write a test with two Act calls, break the second behaviour, and notice how long it takes to see why it failed. Then split it.
  4. Add a constructor with a field to an xUnit class and log its hash code in two tests to prove each test gets a new instance.
  5. Replace three separate asserts on a DTO with Assert.Multiple and then with one Assert.Equal on an expected record; break two fields and compare the output.

💻 Code

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);
    }
}

⚠ Common mistakes

  • Mistake: Naming tests 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.
  • Mistake: Several Act calls in one test (create, then update, then delete). Why it is wrong: When it fails you can't tell which behaviour broke, and later steps hide earlier failures. Instead: One test per behaviour; share setup through a helper.
  • Mistake: Believing "one assert per test" is the rule. Why it is wrong: It forces duplicate setup and splits one outcome into many tests. Instead: One behaviour per test; several asserts on that outcome are fine.
  • Mistake: Loops or 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].
  • Mistake: Wrapping the Act in 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>.
  • Mistake: Thirty lines of Arrange copied into every test. Why it is wrong: Noise hides the one value that matters for this case. Instead: A builder or factory with sensible defaults; override only what the test is about.
  • Mistake: Asserting on values the Act didn't produce (re-checking the setup). Why it is wrong: It adds noise and false confidence. Instead: Assert only the outcome of the Act.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions unit tests only, or blurs unit and integration tests Why: Checks they know where unit tests stop and integration tests start
    How to answer

    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.

  2. When: Candidate uses a stub or fake in the Arrange block Why: Checks they can name and choose between the kinds of test doubles
    How to answer

    These are Gerard Meszaros's five test doubles:

    • A dummy only fills a parameter and is never used.
    • A stub returns canned answers so the code takes a particular path.
    • A fake is a simplified implementation that really works, such as an in-memory repository. You check its state, not the calls made on it.
    • A mock is set up with expected calls and then verifies the interaction. A spy records calls so you can assert on them afterwards.

    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.

More in Testing Practices

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me