AdvancedLesson 16 of 205 min read

Testing Your Code: Assertions, Boundaries and a Failing Test

Learn why automated tests matter, write a small test harness with real assertions for a happy hour price rule, find a boundary bug with a failing test, fix it, and see how xUnit expresses the same ideas.

In this lesson you will

  • Write tests with assertions
  • Test the boundaries of a rule
  • Read a failing test
  • Know how xUnit fits

About 28 minutes

The happy hour that ran too long

Omar changes his price list, and a week later a customer points out that coffee was still cheap at 16:00, after happy hour had finished. Nobody checks every rule after every change, so the mistake lived for days. Automated tests solve this: small programs that call your code with known inputs and compare the results with answers that you expect. They run in seconds, never get tired and let you change code without fear.

A test has three parts: arrange the inputs, act by calling the code, and assert that the result matches what you expected. The inputs worth testing are the typical case and the edge cases, where mistakes live. For a rule that applies from 14:00 up to but not including 16:00, the interesting hours are 13, 14, 15 and 16, the hour before the rule, its first and last hours and the hour after. Expected values must come from the written rules or a hand calculation, never from running the code and copying the output, because then the test can only agree with the code, bugs included. In real projects, a framework such as xUnit, NUnit or MSTest finds the tests, runs them, reports failures with their location and plugs into dotnet test. The ideas are identical to those of the small harness below, which needs no downloads.

Part Meaning
Arrange Create the inputs
Act Call the method under test
Assert Compare the actual and the expected result
Boundary The value just below, at and just above a rule’s limit
Regression test A test added for a bug that was found
static int Price(int hour) => hour >= 14 && hour <= 16 ? 250 : 320;   // BUG: the rule says before 16
int passed = 0, failed = 0;
void Check(string name, int expected, int actual)
{
    if (expected == actual) { passed++; Console.WriteLine($"PASS {name}"); }
    else { failed++; Console.WriteLine($"FAIL {name}: expected {expected} but was {actual}"); }
}
foreach (var (hour, expected) in new[] { (9, 320), (13, 320), (14, 250), (15, 250), (16, 320), (17, 320) })
    Check($"coffee at {hour}:00", expected, Price(hour));
try { Price(-1); Console.WriteLine("no exception for -1"); } catch (ArgumentException) { }
Console.WriteLine($"{passed} passed, {failed} failed");
return failed == 0 ? 0 : 1;
PASS coffee at 9:00
PASS coffee at 13:00
PASS coffee at 14:00
PASS coffee at 15:00
FAIL coffee at 16:00: expected 320 but was 250
PASS coffee at 17:00
no exception for -1
5 passed, 1 failed

The run reported 5 passed and 1 failed, and the process exited with code 1, which is how a build system learns that something is wrong. The failure is “coffee at 16:00: expected 320 but was 250”. The boundary at 16:00 exposed the bug, because the code uses <= 16 where the rule says before 16. The hours 14 and 15 passed, and so did the hours well outside the rule, so a suite that only tried typical values would have missed it. The message shows both the expected and the actual value, so the cause is clear without a debugger.

Fixing the bug is a one-character change, from <= to <. After the fix the same table of cases passes, and from then on the 16:00 case is a regression test that stops the rule from silently breaking again. A useful habit is to write the failing test first, watch it fail for the right reason, fix the code and watch it pass, which proves that the test can actually fail.

static int Price(int hour) => hour >= 14 && hour < 16 ? 250 : 320;
int passed = 0, failed = 0;
void Check(string name, int expected, int actual)
{
    if (expected == actual) { passed++; Console.WriteLine($"PASS {name}"); }
    else { failed++; Console.WriteLine($"FAIL {name}: expected {expected} but was {actual}"); }
}
foreach (var (hour, expected) in new[] { (9, 320), (13, 320), (14, 250), (15, 250), (16, 320), (17, 320) })
    Check($"coffee at {hour}:00", expected, Price(hour));
Console.WriteLine($"{passed} passed, {failed} failed");
return failed == 0 ? 0 : 1;
PASS coffee at 9:00
PASS coffee at 13:00
PASS coffee at 14:00
PASS coffee at 15:00
PASS coffee at 16:00
PASS coffee at 17:00
6 passed, 0 failed

After the fix, all 6 cases pass with 0 failures, and the exit code is 0. The expected values in the table, 320, 320, 250, 250, 320, 320, were written from the rule, 250 from 14:00 up to 16:00 and 320 otherwise, before the program ran. For the failing case, 16:00 is the first hour after happy hour ends, so the price is back to 320.

How xUnit does it

A framework removes the boilerplate that the harness wrote by hand. With xUnit you mark a method with [Fact], or with [Theory] and [InlineData] for a table of cases, and use Assert.Equal and Assert.Throws. The dotnet test command finds all tests, runs them and reports failures. The example below was not run in the course environment, because it needs the xUnit packages from NuGet, so check the official xUnit documentation for the current setup.

using Xunit;

public class PriceTests
{
    [Theory]
    [InlineData(13, 320)]
    [InlineData(14, 250)]
    [InlineData(15, 250)]
    [InlineData(16, 320)]
    public void CoffeePriceFollowsHappyHour(int hour, int expected)
        => Assert.Equal(expected, Pricing.Price(hour));
}
A test that cannot fail is worthless

Break the code on purpose once and make sure that a test turns red. Then you know that it is checking something.

Test the boundaries

For every rule with a limit, test the values just below, exactly at and just above it. Most bugs live at the edges.

About this course

Every program in this lesson was built and run with the .NET 8 SDK and C# 12 while the course was written. .NET and C# release every year, so check the official Microsoft documentation for the current version and for features added after .NET 8. The xUnit snippet is shown but was not run in the course environment.

Practice

Write tests for a method that returns the weekday name for numbers 1 to 7, including 0 and 8. Add a regression test for a bug of your own. Then break the code deliberately and check that at least one test fails.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What are the three parts of a test?

  1. Arrange, act, assert
  2. Read, write, run
  3. Compile, link, load
  4. Plan, buy, sell

Set up, call, compare.

Which input found the bug?

  1. The hour 9
  2. The hour 13
  3. Every hour
  4. 16:00, the hour after the rule ends

The boundary.

Where should expected values come from?

  1. The output of the code under test
  2. A random choice
  3. The test name
  4. The written rules or a hand calculation

Otherwise the test copies the bug.

What does a non-zero exit code tell a build system?

  1. All passed
  2. The file is big
  3. A test failed
  4. The tests are slow

The harness returned 1.

What is a regression test?

  1. A speed test
  2. A colour test
  3. A test that keeps a fixed bug from returning
  4. A compiler test

Add one for each bug.

Summary

  • Tests call code with known inputs and compare with expected answers.
  • Boundaries find the most bugs.
  • The failing test showed the bug and the fix turned it green.
  • Expected values come from the rules, not from the code.

Next lesson

Lesson 17 covers nullable reference types, generics and delegates.

Questions

Do I need xUnit to test?

No, but a framework saves effort and integrates with tools. Start with plain assertions to understand the ideas.

How many tests are enough?

Enough to cover the rules and their boundaries. Quality matters more than quantity.

What is test-driven development?

Writing a failing test first, then the code that passes it, then tidying up. Some teams use it as a habit.

Progress is saved in this browser.