Skip to content

Test the Planner

The Course
•
20 min study

The planner has its own set of checks. They use the same Planner.cs as the application with a different starting file, Checks.cs, because a program can have only one file of top-level statements. They never touch standard input. That's a benefit of keeping the rules in Planner: they can be tested without any input or output.

Planner checks C#
#nullable enable using StudyPlanner; int failures = 0; void Check(bool passed, string name) { if (!passed) { Console.WriteLine($"FAILED: {name}"); failures++; } } // Parsing Check(Planner.ParseTask("25 0 Read chapter") == new StudyTask("Read chapter", 25, false), "parses a todo"); Check(Planner.ParseTask("10 1 Review") == new StudyTask("Review", 10, true), "parses a done task"); Check(Planner.ParseTask("1 0 Short") is not null, "accepts 1 minute"); Check(Planner.ParseTask("180 0 Long") is not null, "accepts 180 minutes"); Check(Planner.ParseTask("0 0 Zero") is null, "rejects 0 minutes"); Check(Planner.ParseTask("181 0 Too long") is null, "rejects 181 minutes"); Check(Planner.ParseTask("-5 0 Negative") is null, "rejects negative minutes"); Check(Planner.ParseTask("ten 0 Words") is null, "rejects text minutes"); Check(Planner.ParseTask("25 2 Flag") is null, "rejects a flag other than 0 or 1"); Check(Planner.ParseTask("25 0") is null, "rejects a missing title"); Check(Planner.ParseTask("25 0 ") is null, "rejects a blank title"); Check(Planner.ParseTask("") is null, "rejects an empty line"); Check(Planner.ParseTask("25 0 " + new string('x', 40)) is not null, "accepts a 40 character title"); Check(Planner.ParseTask("25 0 " + new string('x', 41)) is null, "rejects a 41 character title"); // Adding var planner = new Planner(); Check(planner.Summarize() == new Summary(0, 0, 0, 0), "an empty plan totals zero"); Check(!planner.Add(new StudyTask("Bad", 0, false)), "Add refuses an invalid task"); Check(planner.Tasks.Count == 0, "a refused task is not stored"); for (int i = 0; i < Planner.MaxTasks; i++) { Check(planner.Add(new StudyTask("Task", 1, false)), "Add accepts up to the limit"); } Check(!planner.Add(new StudyTask("Extra", 1, false)), "Add refuses task 101"); Check(planner.Tasks.Count == Planner.MaxTasks, "the limit holds"); // Completing and summarizing var small = new Planner(); small.Add(new StudyTask("Read", 25, false)); small.Add(new StudyTask("Review", 10, true)); Check(small.Summarize() == new Summary(2, 35, 10, 25), "totals split done and remaining"); Check(small.Complete(0), "Complete accepts a valid index"); Check(small.Summarize() == new Summary(2, 35, 35, 0), "completing moves minutes"); Check(small.Complete(0), "completing twice is allowed"); Check(small.Summarize() == new Summary(2, 35, 35, 0), "completing twice does not double count"); Check(!small.Complete(-1), "Complete refuses a negative index"); Check(!small.Complete(2), "Complete refuses an index past the end"); if (failures > 0) { Console.WriteLine($"{failures} checks failed"); Environment.Exit(1); } Console.WriteLine("Planner checks passed"); #nullable enable namespace StudyPlanner; public record StudyTask(string Title, int Minutes, bool Done); public record Summary(int Tasks, int Planned, int Completed, int Remaining); public class Planner { public const int MaxTasks = 100; public const int MaxMinutes = 180; public const int MaxTitleLength = 40; private readonly List<StudyTask> tasks = new(); public IReadOnlyList<StudyTask> Tasks => tasks; public static bool IsValid(StudyTask task) { return task.Minutes >= 1 && task.Minutes <= MaxMinutes && task.Title.Trim().Length >= 1 && task.Title.Trim().Length <= MaxTitleLength; } // Returns null for a line that does not describe a valid task. public static StudyTask? ParseTask(string line) { string[] parts = line.Split(' ', 3); if (parts.Length != 3 || !int.TryParse(parts[0], out int minutes)) { return null; } if (parts[1] != "0" && parts[1] != "1") { return null; } var task = new StudyTask(parts[2].Trim(), minutes, parts[1] == "1"); return IsValid(task) ? task : null; } public bool Add(StudyTask task) { if (!IsValid(task) || tasks.Count >= MaxTasks) { return false; } tasks.Add(task); return true; } public bool Complete(int index) { if (index < 0 || index >= tasks.Count) { return false; } tasks[index] = tasks[index] with { Done = true }; return true; } public Summary Summarize() { int planned = 0; int completed = 0; foreach (StudyTask task in tasks) { planned += task.Minutes; if (task.Done) { completed += task.Minutes; } } return new Summary(tasks.Count, planned, completed, planned - completed); } }

A healthy run prints Planner checks passed. A failure prints a named FAILED line and ends with exit code 1.

Records make checks easy

Because StudyTask and Summary compare by value, a single == checks every field at once. Compare one line of the check with what it would otherwise take. Predict these two results.

Comparing a whole result C#
var actual = new Summary(2, 35, 10, 25);

Console.WriteLine(actual == new Summary(2, 35, 10, 25));
Console.WriteLine(actual == new Summary(2, 35, 10, 24));

record Summary(int Tasks, int Planned, int Completed, int Remaining);
Check your prediction
Text
True
False

What the checks cover

Read Checks.cs and match each group to the brief.

  • Parsing: valid lines, each boundary from both sides (0, 1, 180 and 181 minutes; 40 and 41 characters), and each kind of malformed line.
  • Adding: a refused task isn't stored, and the 100-task limit holds on exactly task 101.
  • Completing: a repeat changes nothing, and indexes -1 and "one past the end" are both refused.
  • Summarizing: the empty plan, then a plan that mixes done and todo tasks.

Do the checks really work?

A check that can't fail is worse than none, since it gives false confidence. So test the tests: make a realistic mistake, and see whether anything notices. This is called mutation testing. Work through these in the Planner.cs tab above, restoring the code after each one.

  1. In IsValid, change task.Minutes >= 1 to task.Minutes >= 0.
  2. In Add, change tasks.Count >= MaxTasks to tasks.Count > MaxTasks.
  3. In Complete, change Done = true to Done = !tasks[index].Done.
  4. In Summarize, change if (task.Done) to if (true).

Each one should produce at least one FAILED line. This site's own build runs these and several more automatically, so a check that stops catching one of them is itself reported as a failure. Mutation 3 is worth a second look: it passes every check that completes a task only once. It takes the "completing twice" check to catch it.

Your turn

Checks aren't only for code that exists. Here, you write the check before the code, so the failure tells you exactly what to build.

Exercise

Check a pending count

Write PendingCount(List<StudyTask> tasks), which returns the number of tasks not yet done. Write checks first, using the Check helper: an empty list gives 0, a mix of two todo and one done gives 2, and all done gives 0. Run them and see them fail against a method that always returns -1. Then write the real method. A correct run prints Pending checks passed.

Your workspace C#
Console.WriteLine(PendingCount(new List<StudyTask>()));

static int PendingCount(List<StudyTask> tasks)
{
    return -1;
}

record StudyTask(string Title, int Minutes, bool Done);
Hint 1: the idea

Only tasks with Done false add to the count. Think of the empty list as well as the normal case.

Hint 2: a first step

Copy the Check helper with its failures variable, and write the empty-list check first. It should fail against the supplied method.

Show one solution
C#
int failures = 0;

Check(PendingCount(new List<StudyTask>()) == 0, "an empty list has none pending");
Check(PendingCount(new List<StudyTask>
{
    new StudyTask("Read", 25, false),
    new StudyTask("Review", 10, true),
    new StudyTask("Practice", 40, false),
}) == 2, "counts only todo tasks");
Check(PendingCount(new List<StudyTask> { new StudyTask("Read", 25, true) }) == 0, "done tasks aren't pending");

if (failures == 0)
{
    Console.WriteLine("Pending checks passed");
}

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

static int PendingCount(List<StudyTask> tasks)
{
    int pending = 0;
    foreach (StudyTask task in tasks)
    {
        if (!task.Done)
        {
            pending++;
        }
    }
    return pending;
}

record StudyTask(string Title, int Minutes, bool Done);
Text
Pending checks passed

The checks cover an empty list, a mixture, and a list where every task is done, so a method that counted all tasks, or the done ones, would fail at least one. Check prints only failures, so the single line at the end appears only when all three pass.

Mutate your own solution: change !task.Done to task.Done. How many of your checks fail? Would one check have been enough to catch it?

Was this article helpful?

Your response is saved on this device.