Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 14

    What Makes a Good Unit Test in .NET: The Answer Interviewers Want

    What this lesson teaches

    A unit test checks one behavior in memory, without infrastructure. Learn what makes a good unit test in .NET and how to explain it in an interview.

    A behavior is something your code promises to do for a particular input or situation. For example, a shipping rule might promise free delivery when the order subtotal reaches 50.

    After this lesson, you can explain:

    • What counts as a unit test, and where integration testing begins.
    • How to choose cases and name tests clearly.
    • Why a passing test might still be useless.
    • What belongs in a unit test and what does not.

    If testing is new to you, start with testing behavior and debugging failures.

    What is a unit test?

    In this lesson, we focus each unit test on one behavior. Microsoft's Testing in .NET guidance says unit tests should test code within the developer's control. A unit test runs in memory, is fast and repeatable, and checks its own result.

    It does not need infrastructure: outside facilities such as a database, network connection, or file system. It should not depend on the real clock either. Otherwise, the same input might pass today and fail tomorrow.

    For this lesson, a unit test and the code it checks run within one process, without starting another service.

    The word unit does not have to mean one method or one class. There are two common approaches:

    • In the classical view, several real classes may work together in memory to provide one behavior.
    • In the mockist view, the test usually checks one class and replaces the other objects it calls with controlled substitutes.

    You may also hear these called the Detroit (or Chicago) school and the London school, respectively.

    This lesson uses the classical view. A few classes working together do not automatically turn a test into an integration test.

    The mistake to avoid. Do not count classes to classify a test. Say which meaning of “unit” you use, then describe what the test actually exercises.

    In an interview, say: “Classical, or Detroit/Chicago, tests check a unit of behavior and allow real in-memory collaborators. Mockist, or London, tests usually isolate one class with controlled substitutes. I say which one I mean.”

    Where unit testing ends

    An integration test checks whether parts of a system work together, often across a real edge of the program such as a database or a network call. For example, it might check whether application code sends the right query to a real database.

    Speed alone is not the dividing line. A fast database test still depends on a database.

    For this course, tests that need any of these belong in the integration category:

    What the test needsWhat it checks beyond a unit
    A real databaseWhether the code and database work together
    Real HTTPWhether communication with another running service works
    The ASP.NET Core hostWhether application startup and request handling work together
    A dependency injection containerWhether object registration and construction work together

    Do not unit test the framework's own behavior. A framework supplies reusable application structure and services, such as ASP.NET Core's request handling. Your tests should check your decisions, not prove that its built-in features work.

    Ordinary properties that only store and return a value usually need no dedicated tests. Add tests when a property enforces a rule. Wiring means registering and connecting application parts; check that with integration tests.

    For a concrete next step, see building an HTTP contract test that can catch a real regression.

    The mistake to avoid. Do not call a test a unit test just because it finishes quickly. Check which real boundaries it crosses.

    In an interview, say: “Integration tests check parts working together, including boundaries such as databases, HTTP, or application startup. Speed alone does not distinguish them. I unit test my rules, not framework code or trivial properties, and use integration tests for wiring.”

    See it in code: test a shipping rule

    Our rule is simple: shipping costs 5 below a subtotal of 50, and is free from 50 onward. Negative subtotals are invalid.

    Choose cases from that rule before writing the checks:

    SubtotalExpected shippingWhy choose it?
    105A normal paid-shipping order
    49.995Just below the free-shipping boundary
    500Exactly at the boundary
    1000A normal free-shipping order
    -1An exceptionAn invalid input

    A boundary is a point where the required behavior changes. Here, 50 is that point. We use amounts expressed to two decimal places, so 49.99 is the case immediately below it.

    Work out expected results from the written rule. Do not run the method and copy whatever it returns into the test.

    An assertion is a check that reports a test failure when the actual result does not match the expected result. The small Check helper below serves that purpose without a test library.

    Predict the output before running this program. The first four checks use independently chosen expectations. The final check deliberately demonstrates a bad expectation.

    C#Runs
    Check("Cost_NormalSubtotal_ReturnsFive", 5m, Shipping.Cost(10m));
    Check("Cost_JustBelowFifty_ReturnsFive", 5m, Shipping.Cost(49.99m));
    Check("Cost_AtFifty_ReturnsZero", 0m, Shipping.Cost(50m));
    Check("Cost_AboveFifty_ReturnsZero", 0m, Shipping.Cost(100m));
    
    // A broken rule charges shipping at exactly 50.
    decimal subtotal = 50m;
    decimal copiedExpected = subtotal > 50m ? 0m : 5m;
    decimal brokenActual = BrokenCost(subtotal);
    Check("Copied formula: misleading result", copiedExpected, brokenActual);
    
    static decimal BrokenCost(decimal subtotal) => subtotal > 50m ? 0m : 5m;
    
    static void Check(string name, decimal expected, decimal actual)
    {
        if (expected != actual)
        {
            throw new Exception($"{name}: expected {expected}, got {actual}");
        }
    
        Console.WriteLine($"{name}: PASS");
    }
    
    public static class Shipping
    {
        public static decimal Cost(decimal subtotal)
        {
            if (subtotal < 0m)
            {
                throw new ArgumentOutOfRangeException(nameof(subtotal));
            }
    
            return subtotal >= 50m ? 0m : 5m;
        }
    }
    Output
    Cost_NormalSubtotal_ReturnsFive: PASS
    Cost_JustBelowFifty_ReturnsFive: PASS
    Cost_AtFifty_ReturnsZero: PASS
    Cost_AboveFifty_ReturnsZero: PASS
    Copied formula: misleading result: PASS

    Inside Check, a mismatch throws an exception instead of printing success. You do not have to inspect two numbers yourself to decide whether the check passed.

    The final check also prints PASS, but it proves nothing useful. BrokenCost uses > instead of >=, so it incorrectly charges 5 at exactly 50. The expected-value calculation repeats that same mistake.

    flowchart TD
        R["Written shipping rule"] -->|determines| E["Expected shipping: 0"]
        C["Shipping.Cost at 50"] -->|produces| A["Actual shipping"]
        E -->|compared by| T["Check"]
        A -->|compared by| T

    The expected result comes from the rule, while the actual result comes from the code being tested.

    Now deliberately change Shipping.Cost from >= 50m to > 50m. Run it again. You will see two PASS lines, then the program stops with an unhandled exception: “Cost_AtFifty_ReturnsZero: expected 0, got 5”. The later checks do not run. In xUnit, the test runner shows this test as failed (red) and still runs the others. Restore the correct code afterward. “Going red” means observing a failing test; it confirms that this check can detect this particular defect.

    The mistake to avoid. Do not calculate an expectation by repeating the formula from the real code you are testing (often called production code). Both calculations can share a bug and agree on the wrong answer.

    In an interview, say: “I choose cases from the rule: normal inputs, boundaries, and invalid input. I work out expected results independently, then deliberately break the code once to confirm that the relevant test fails.”

    Arrange, Act, Assert and clear names

    Arrange, Act, Assert, often shortened to AAA, separates a test into three parts. Arrange prepares the input and any required objects. Act performs the behavior once. Assert checks the outcome.

    In the console example, choosing 50m is Arrange, calling Shipping.Cost(50m) is Act, and Check(...) is Assert.

    Use a consistent three-part name: method, scenario, expected result. For example, Cost_AtFifty_ReturnsZero tells you what failed without opening the test.

    A test framework is a library that identifies test methods and provides assertions. The following example uses xUnit.

    In xUnit, [Fact] declares a test method run by the test runner. [Theory] represents tests that run the same code with different input arguments, and [InlineData] supplies the values. Microsoft's xUnit tutorial introduces these attributes. Assert.Equal compares expected and actual results. Assert.Throws<T> checks that the operation throws an exception of exactly type T, not a derived type, and returns it so you can check it further. Use Assert.ThrowsAny<T> when derived exception types should also be accepted.

    This is test-project code, not a standalone console program. It needs the xUnit v3 package (xunit.v3) in a test project.

    C#
    using System;
    using Xunit;
    
    public class ShippingTests
    {
        [Fact]
        public void Cost_AtFifty_ReturnsZero()
        {
            // Arrange
            decimal subtotal = 50m;
    
            // Act
            decimal actual = Shipping.Cost(subtotal);
    
            // Assert
            Assert.Equal(0m, actual);
        }
    
        [Theory]
        [InlineData(1000, 500)]
        [InlineData(4999, 500)]
        [InlineData(5000, 0)]
        [InlineData(10000, 0)]
        public void Cost_ValidSubtotal_ReturnsExpectedShipping(
            int subtotalCents, int expectedCents)
        {
            // Arrange
            decimal subtotal = subtotalCents / 100m;
            decimal expected = expectedCents / 100m;
    
            // Act
            decimal actual = Shipping.Cost(subtotal);
    
            // Assert
            Assert.Equal(expected, actual);
        }
    
        [Fact]
        public void Cost_NegativeSubtotal_ThrowsArgumentOutOfRangeException()
        {
            Assert.Throws<ArgumentOutOfRangeException>(
                () => Shipping.Cost(-1m));
        }
    }
    
    public static class Shipping
    {
        public static decimal Cost(decimal subtotal)
        {
            if (subtotal < 0m)
            {
                throw new ArgumentOutOfRangeException(nameof(subtotal));
            }
    
            return subtotal >= 50m ? 0m : 5m;
        }
    }

    The theory expresses the same four valid-input checks as the console example. C# attribute arguments cannot be decimal values, so [InlineData] cannot hold 49.99m. The rows store whole cents as int, and the test divides by 100m to get decimal amounts. The expected amounts remain independently chosen constants.

    The separate boundary fact illustrates AAA explicitly. In a real project, you could keep that case in the theory rather than duplicate it.

    In the invalid-input test, the lambda () => Shipping.Cost(-1m) lets Assert.Throws call the operation and examine the exception. Here, Act happens inside Assert because the exception is the outcome being checked.

    The mistake to avoid. Do not put several unrelated actions into one test. A failure should identify one broken behavior, not leave you investigating a whole workflow.

    In an interview, say: “I use Arrange, Act, Assert and consistent method–scenario–expected-result names. Each test checks one behavior. A theory lets me express several inputs for that same behavior without repeating the test body.”

    What makes a unit test good?

    Microsoft's “Characteristics of good unit tests” guidance describes useful characteristics:

    • Fast: It takes little time, so you can run it frequently.
    • Isolated: It stands alone and does not require outside facilities or another test's work.
    • Repeatable: With nothing relevant changed, it produces the same result.
    • Self-checking: It reports success or failure without manual inspection.
    • Timely: Writing the test should not take much longer than writing the code it checks. If testing is slow and hard, consider a design that is easier to test.

    Deterministic means the same controlled conditions produce the same result. Avoid shared data that other tests change, dependence on test order, and the real clock. If time affects a rule, give the code a controlled time input for the test.

    The common memory aid FIRST uses the terms Fast, Isolated or Independent, Repeatable, Self-validating, and Timely. It is not a Microsoft-coined name. In the traditional memory aid, Timely often means writing tests at the same time as the code, rather than Microsoft's emphasis on how long tests take to write.

    A good test also checks behavior rather than internal steps. If the shipping result stays correct after you reorganize the calculation, the test should usually stay unchanged.

    One behavior does not necessarily mean one assertion. Several assertions can describe one result. The important question is whether a failure points to one clear broken promise.

    Generally, do not test private methods directly. Test them through the public behavior that uses them, so you can reorganize the internals without rewriting tests. When to mock and when not to covers private methods in more depth.

    The mistake to avoid. Do not make one test depend on another having run first. It must work when selected and run alone.

    In an interview, say: “I use FIRST: Fast, Isolated or Independent, Repeatable, Self-validating, and Timely. A good test has a clear name and checks one behavior, not implementation details. Microsoft's Timely guidance also asks whether tests take disproportionately long to write.”

    Check yourself

    Which test belongs in the integration category used in this lesson?

    A A shipping calculation checked with four fixed inputs
    B Three in-memory classes calculating one discount
    C A very fast check that queries a real database
    D A check that supplies a fixed date to a pricing rule
    Show answer

    Correct answer: C

    The database is a real infrastructure dependency. Finishing quickly does not make the check a unit test.

    A shipping test calculates its expected value by copying the production formula. What is the main risk?

    A The test runs the formula twice, so it becomes noticeably slower
    B Sharing the production logic turns it into an integration test
    C xUnit flags computed expected values and fails the test at run time
    D A defect copied into both calculations lets the test pass anyway
    Show answer

    Correct answer: D

    Agreement is not enough when both sides repeat the same mistake. Work out the expected result from the rule independently.

    Going deeper

    A regression is a defect introduced into behavior that previously worked. Unit tests help catch regressions, but the checks above cannot prove that a web endpoint uses Shipping.Cost correctly. That connection needs a broader test.

    Writing tests early gives you feedback while the design is still easy to change. You can still assess an existing test with the same practical question: would it fail if its promised behavior broke?

    Sources

    Practice

    Practice test: Practice: What Makes a Good Unit Test in .NET: The Answer Interviewers Want7 questions · 1 mark each, no negative markingFull Access
    Take the test
    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 30 Nov 2026 ·