Skip to content

Checking Your Code

The Course
•
25 min study

Running a program once and seeing a plausible answer tells you very little. A check states what the result should be and complains when it isn't. Checks keep working after you've moved on, so they catch mistakes that you introduce later, when you've forgotten the details.

Professional C# projects use test frameworks such as xUnit. You don't need one to understand the idea. A check is just a comparison and a message, so you can write your own helper in a few lines.

A small helper

This Check method has no static, on purpose. It needs to update failures, which belongs to the main program, so it's allowed to see that variable. Printing only failures means a healthy run stays quiet.

One check should fail: which? C#
int failures = 0;

Check(IsValid(1), "1 is valid");
Check(IsValid(180), "180 is valid");
Check(!IsValid(0), "0 is invalid");
Check(!IsValid(181), "181 is invalid");
Console.WriteLine($"{failures} failed");

void Check(bool passed, string name)
{
    if (!passed)
    {
        Console.WriteLine($"FAILED: {name}");
        failures++;
    }
}

static bool IsValid(int minutes)
{
    return minutes >= 1 && minutes < 180;
}
Check your prediction
Text
FAILED: 180 is valid
1 failed

Fix IsValid so that nothing fails. The message tells you which behaviour broke, not just that something did, so it's worth wording carefully.

Choosing inputs that find mistakes

An all-valid example such as 25 passes for both < 180 and <= 180, so it can't tell them apart. The most useful inputs are:

  • Both sides of each boundary: 0 and 1, then 180 and 181.
  • Empty or zero cases: an empty list, an empty string, a count of 0.
  • A normal case: something in the middle, to be sure the common path works.

For each check, ask yourself: "What mistake would make this fail?" If you can't name one, the check might not be adding anything.

Why not Debug.Assert?

You may see Debug.Assert in other code. It looks like a check, but it only runs in debug builds. In a release build, the compiler removes the call entirely. The browser runtime here compiles without debug mode, so this assertion, which is false, does nothing at all.

A false assertion that passes silently C#
using System.Diagnostics;

Debug.Assert(1 == 2, "This is false");
Console.WriteLine("Still running");
Check your prediction
Text
Still running

using System.Diagnostics; at the top makes that namespace's names available. Everyday ones like Console and List come ready for use, and others need a using line. For the checks in this course, use your own helper, which always runs.

Stop on failure

A test run should end with a result that tools can read, not just some text. Environment.Exit(1) ends the program with a non-zero exit code, which by convention means failure. The widget shows it in the output as a failed run. You can use the same line in automated checks when you work locally.

Exit with a failure code C#
int failures = 1;

if (failures > 0)
{
    Console.WriteLine($"{failures} checks failed");
    Environment.Exit(1);
}
Console.WriteLine("All checks passed");
Check your prediction
Text
1 checks failed
Program exited with status 1.

Your turn

Exercise

Check a pass mark

Write Passed(int score), which returns true for scores from 50 to 100 inclusive. Using the Check helper, write checks for both boundaries of that range, including just outside each one. Finish by printing Checks done. A correct method prints only that line.

Your workspace C#
Console.WriteLine("Checks done");
Hint 1: the idea

There are two boundaries, so that makes four interesting scores: one on and one off each edge.

Hint 2: a first step

Copy the Check helper and the failures variable from above, and start with one check for a score of 50.

Show one solution
C#
int failures = 0;

Check(Passed(50), "50 passes");
Check(!Passed(49), "49 fails");
Check(Passed(100), "100 passes");
Check(!Passed(101), "101 is out of range");
Console.WriteLine("Checks done");

void Check(bool passed, string name)
{
    if (!passed)
    {
        Console.WriteLine($"FAILED: {name}");
        failures++;
    }
}

static bool Passed(int score)
{
    return score >= 50 && score <= 100;
}
Text
Checks done

The checks sit on both sides of each boundary, 49 and 50, 100 and 101, because that's where a wrong > or >= shows up. Check prints only when something fails, so a clean run prints just Checks done.

Now test your checks. Change >= to > in Passed and confirm that one check fails, then restore it. Do the same for <=. Breaking code on purpose is how you find out whether your checks would catch a real mistake.

Was this article helpful?

Your response is saved on this device.