Skip to content

Test the Tracker

The Course
•
20 min study

The checks use the same files as the application, with Checks.cs in place of Program.cs. Press Run. A healthy result is a single line.

Tracker checks C#
#nullable enable using TaskTracker; int failures = 0; void Check(bool passed, string name) { if (!passed) { Console.WriteLine($"FAILED: {name}"); failures++; } } var today = new DateOnly(2026, 11, 2); // Adding and stable ids var tracker = new Tracker(); Check(tracker.Add(" ", Priority.Low, today) is Fail<TaskItem>, "refuses a blank title"); Check(tracker.Add(new string('x', 61), Priority.Low, today) is Fail<TaskItem>, "refuses 61 characters"); Check(tracker.Tasks.Count == 0, "refused tasks are not stored"); Check(tracker.Add(new string('x', 60), Priority.Low, today) is Ok<TaskItem>, "accepts 60 characters"); Check(tracker.Add(" Trim me ", Priority.High, today) is Ok<TaskItem> { Value: { Id: 2, Title: "Trim me" } }, "trims and numbers"); Check(tracker.Remove(2) is Ok<TaskItem>, "removes a task"); Check(tracker.Add("Next", Priority.Low, today) is Ok<TaskItem> { Value.Id: 3 }, "never reuses an id"); // Completing Check(tracker.Complete(3) is Ok<TaskItem> { Value.Done: true }, "completes a task"); Check(tracker.Complete(3) is Ok<TaskItem> { Value.Done: true }, "completing twice leaves it done"); Check(tracker.Complete(99) is Fail<TaskItem>, "refuses an unknown id to complete"); Check(tracker.Remove(99) is Fail<TaskItem>, "refuses an unknown id to remove"); // Reports var tasks = new List<TaskItem> { new(1, "Late", Priority.Low, new DateOnly(2026, 11, 1)), new(2, "Today", Priority.High, today), new(3, "Today low", Priority.Low, today), new(4, "Finished late", Priority.High, new DateOnly(2026, 1, 1), Done: true), }; Report report = Reports.Build(tasks, today); Check(report.Open == 3 && report.Done == 1, "splits open and done"); Check(report.Overdue == 1, "due today is not overdue, and done is never overdue"); Check(report.OpenByPriority[Priority.Low] == 2 && report.OpenByPriority[Priority.High] == 1, "groups open by priority"); Check(!report.OpenByPriority.ContainsKey(Priority.Normal), "an empty group has no entry"); Check(Reports.Ordered(tasks).Select(task => task.Id).SequenceEqual(new[] { 1, 2, 3, 4 }), "orders open, due, priority"); // Saving and loading through a fake store var store = new FakeStore(); var saving = new Tracker(); saving.Add("Keep", Priority.Normal, today); saving.Add("Gone", Priority.Normal, today); saving.Remove(2); Check(saving.Save(store) is Ok<int> { Value: 1 }, "saves through the store"); var loading = new Tracker(); loading.Add("Replaced", Priority.Low, today); Check(loading.Load(store) is Ok<int> { Value: 1 }, "loads through the store"); Check(loading.Tasks.Single().Title == "Keep", "load replaces the tasks"); Check(loading.Add("After", Priority.Low, today) is Ok<TaskItem> { Value.Id: 2 }, "ids continue after the highest loaded"); var failing = new Tracker(); failing.Add("Survivor", Priority.Low, today); Check(failing.Load(new FakeStore { Failure = new IOException("disk") }) is Fail<int>, "reports a failed load"); Check(failing.Save(new FakeStore { Failure = new IOException("disk") }) is Fail<int>, "reports a failed save"); var duplicate = new FakeStore { Saved = new List<TaskItem> { new(1, "A", Priority.Low, today), new(1, "B", Priority.Low, today) } }; Check(failing.Load(duplicate) is Fail<int>, "refuses duplicate ids"); var gaps = new FakeStore { Saved = new List<TaskItem> { new(2, "A", Priority.Low, today), new(7, "B", Priority.Low, today) } }; var afterGaps = new Tracker(); afterGaps.Load(gaps); Check(afterGaps.Add("C", Priority.Low, today) is Ok<TaskItem> { Value.Id: 8 }, "ids continue after the highest loaded id"); var blank = new FakeStore { Saved = new List<TaskItem> { new(1, " ", Priority.Low, today) } }; Check(failing.Load(blank) is Fail<int>, "refuses a blank saved title"); Check(failing.Tasks.Single().Title == "Survivor", "a failed load changes nothing"); // The real file store, including damaged and missing files var file = new JsonFileStore("checks.json"); Check(new Tracker().Load(new JsonFileStore("missing.json")) is Fail<int>, "a missing file is a failure, not a crash"); File.WriteAllText("damaged.json", "{ not json"); Check(new Tracker().Load(new JsonFileStore("damaged.json")) is Fail<int>, "a damaged file is a failure, not a crash"); foreach (string invalid in new[] { "[null]", "null", "[{\"Id\":1,\"Title\":\"Test\",\"Priority\":99,\"Due\":\"2026-11-02\"}]", "{ not json" }) { File.WriteAllText("invalid.json", invalid); var kept = new Tracker(); kept.Add("Keep", Priority.Low, today); Check(kept.Load(new JsonFileStore("invalid.json")) is Fail<int>, $"refuses saved data: {invalid}"); Check(kept.Tasks.Single().Title == "Keep", $"keeps the tasks after: {invalid}"); Check(kept.Add("Next", Priority.Low, today) is Ok<TaskItem> { Value.Id: 2 }, $"keeps the next id after: {invalid}"); } File.WriteAllText("invalid.json", "[]"); var emptied = new Tracker(); emptied.Add("Replaced", Priority.Low, today); Check(emptied.Load(new JsonFileStore("invalid.json")) is Ok<int> { Value: 0 } && emptied.Tasks.Count == 0, "an empty list is valid"); Check(emptied.Add("First", Priority.Low, today) is Ok<TaskItem> { Value.Id: 1 }, "ids restart after loading an empty list"); File.Delete("invalid.json"); saving.Save(file); var reloaded = new Tracker(); reloaded.Load(file); Check(reloaded.Tasks.SequenceEqual(saving.Tasks), "a file round trip keeps every field"); File.Delete("checks.json"); File.Delete("damaged.json"); // Commands var commands = new Commands(new Tracker(), new FixedClock(today)); Check(commands.Execute(" ").Count == 0, "a blank line prints nothing"); Check(commands.Execute("add High 2026-11-03 Plan week").Single() == "Added 1: Plan week", "add reports the id"); Check(commands.Execute("add Urgent 2026-11-03 x").Single().StartsWith("Error"), "refuses an unknown priority"); Check(commands.Execute("add 7 2026-11-03 x").Single().StartsWith("Error"), "refuses a numeric priority"); Check(commands.Execute("add Low 2026-02-30 x").Single().StartsWith("Error"), "refuses an impossible date"); Check(commands.Execute("add Low 2026-11-03").Single().StartsWith("Error"), "refuses a missing title"); Check(commands.Execute("done one").Single().StartsWith("Error"), "refuses a bad id"); Check(commands.Execute("nonsense").Single().StartsWith("Error"), "refuses an unknown command"); Check(commands.Execute("today 2026-11-04").Single() == "Today is 2026-11-04", "today sets the date"); Check(commands.Execute("report")[2] == "Overdue: 1", "the report uses the set date"); if (failures > 0) { Console.WriteLine($"{failures} checks failed"); Environment.Exit(1); } Console.WriteLine("Tracker checks passed"); class FakeStore : ITaskStore { public List<TaskItem> Saved { get; set; } = new(); public Exception? Failure { get; init; } public IReadOnlyList<TaskItem> Load() { if (Failure is not null) { throw Failure; } return Saved; } public void Save(IEnumerable<TaskItem> tasks) { if (Failure is not null) { throw Failure; } Saved = tasks.ToList(); } } #nullable enable using System.Globalization; namespace TaskTracker; // Turns one line of text into output lines, so it can be checked without a console. public class Commands { private readonly Tracker tracker; private IClock clock; public Commands(Tracker tracker, IClock clock) { this.tracker = tracker; this.clock = clock; } public IReadOnlyList<string> Execute(string line) { string[] parts = line.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (parts.Length == 0) { return Array.Empty<string>(); } string argument = parts.Length == 2 ? parts[1] : ""; return parts[0] switch { "add" => Add(argument), "done" => WithId(argument, "Completed", tracker.Complete), "remove" => WithId(argument, "Removed", tracker.Remove), "list" => List(), "report" => BuildReport(), "save" => Store(argument, tracker.Save, "Saved"), "load" => Store(argument, tracker.Load, "Loaded"), "today" => SetToday(argument), _ => Error($"unknown command {parts[0]}"), }; } private static string[] Error(string message) => new[] { $"Error: {message}" }; private static bool TryParseDate(string text, out DateOnly date) { return DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date); } private string[] Add(string argument) { string[] fields = argument.Split(' ', 3, StringSplitOptions.TrimEntries); if (fields.Length != 3) { return Error("usage: add <priority> <yyyy-MM-dd> <title>"); } if (!Enum.TryParse(fields[0], ignoreCase: true, out Priority priority) || !Enum.IsDefined(priority)) { return Error($"unknown priority {fields[0]}"); } if (!TryParseDate(fields[1], out DateOnly due)) { return Error($"bad date {fields[1]}"); } return tracker.Add(fields[2], priority, due) switch { Ok<TaskItem> ok => new[] { $"Added {ok.Value.Id}: {ok.Value.Title}" }, Fail<TaskItem> fail => Error(fail.Error), _ => throw new InvalidOperationException("unknown result"), }; } private static string[] WithId(string argument, string verb, Func<int, Result<TaskItem>> action) { if (!int.TryParse(argument, out int id)) { return Error($"bad id {argument}"); } return action(id) switch { Ok<TaskItem> ok => new[] { $"{verb} {ok.Value.Id}: {ok.Value.Title}" }, Fail<TaskItem> fail => Error(fail.Error), _ => throw new InvalidOperationException("unknown result"), }; } private string[] List() { return Reports.Ordered(tracker.Tasks) .Select(task => $"[{(task.Done ? "x" : " ")}] {task.Id} {task.Priority} {task.Due:yyyy-MM-dd} {task.Title}") .ToArray(); } private string[] BuildReport() { Report report = Reports.Build(tracker.Tasks.ToList(), clock.Today); var lines = new List<string> { $"Open: {report.Open}", $"Done: {report.Done}", $"Overdue: {report.Overdue}", }; foreach (Priority priority in Enum.GetValues<Priority>().Reverse()) { report.OpenByPriority.TryGetValue(priority, out int count); lines.Add($"{priority}: {count}"); } return lines.ToArray(); } private static string[] Store(string path, Func<ITaskStore, Result<int>> action, string verb) { if (path.Length == 0) { return Error("a file name is required"); } return action(new JsonFileStore(path)) switch { Ok<int> ok => new[] { $"{verb} {ok.Value} tasks" }, Fail<int> fail => Error(fail.Error), _ => throw new InvalidOperationException("unknown result"), }; } private string[] SetToday(string argument) { if (!TryParseDate(argument, out DateOnly today)) { return Error($"bad date {argument}"); } clock = new FixedClock(today); return new[] { $"Today is {today:yyyy-MM-dd}" }; } } #nullable enable namespace TaskTracker; public class Tracker { public const int MaxTitleLength = 60; private readonly List<TaskItem> tasks = new(); private int nextId = 1; public IReadOnlyList<TaskItem> Tasks => tasks; public Result<TaskItem> Add(string title, Priority priority, DateOnly due) { string trimmed = title.Trim(); if (trimmed.Length == 0 || trimmed.Length > MaxTitleLength) { return new Fail<TaskItem>($"title must be 1 to {MaxTitleLength} characters"); } var task = new TaskItem(nextId, trimmed, priority, due); nextId++; tasks.Add(task); return new Ok<TaskItem>(task); } public Result<TaskItem> Complete(int id) { int index = tasks.FindIndex(task => task.Id == id); if (index < 0) { return new Fail<TaskItem>($"no task {id}"); } tasks[index] = tasks[index] with { Done = true }; return new Ok<TaskItem>(tasks[index]); } public Result<TaskItem> Remove(int id) { int index = tasks.FindIndex(task => task.Id == id); if (index < 0) { return new Fail<TaskItem>($"no task {id}"); } TaskItem removed = tasks[index]; tasks.RemoveAt(index); return new Ok<TaskItem>(removed); } public Result<int> Save(ITaskStore store) { try { store.Save(tasks); return new Ok<int>(tasks.Count); } catch (IOException e) { return new Fail<int>(e.Message); } } // Replaces the tasks only after everything loaded and validated. public Result<int> Load(ITaskStore store) { IReadOnlyList<TaskItem> loaded; try { loaded = store.Load(); } catch (IOException e) { return new Fail<int>(e.Message); } catch (StoreFormatException e) { return new Fail<int>(e.Message); } // Nullable annotations are not enforced when JSON is read, so a list can hold null. if (loaded.Any(task => task is null)) { return new Fail<int>("saved data has an empty entry"); } if (loaded.Any(task => task.Title is null || task.Title.Trim().Length == 0 || task.Title.Length > MaxTitleLength)) { return new Fail<int>("saved data has an invalid title"); } // An enum accepts any number of its underlying type, such as 99 in a saved file. if (loaded.Any(task => !Enum.IsDefined(task.Priority))) { return new Fail<int>("saved data has an invalid priority"); } if (loaded.Select(task => task.Id).Distinct().Count() != loaded.Count || loaded.Any(task => task.Id < 1)) { return new Fail<int>("saved data has invalid ids"); } tasks.Clear(); tasks.AddRange(loaded); nextId = tasks.Count == 0 ? 1 : tasks.Max(task => task.Id) + 1; return new Ok<int>(tasks.Count); } } #nullable enable namespace TaskTracker; public enum Priority { Low, Normal, High } public record TaskItem(int Id, string Title, Priority Priority, DateOnly Due, bool Done = false); // A result is exactly one of two cases, so a caller has to look before using a value. public abstract record Result<T>; public sealed record Ok<T>(T Value) : Result<T>; public sealed record Fail<T>(string Error) : Result<T>; #nullable enable using System.Text.Json; using System.Text.Json.Serialization; namespace TaskTracker; public interface ITaskStore { IReadOnlyList<TaskItem> Load(); void Save(IEnumerable<TaskItem> tasks); } public class StoreFormatException : Exception { public StoreFormatException(string message, Exception? inner = null) : base(message, inner) { } } public class JsonFileStore : ITaskStore { private static readonly JsonSerializerOptions Options = new() { WriteIndented = true, Converters = { new JsonStringEnumConverter() }, }; private readonly string path; public JsonFileStore(string path) { this.path = path; } public IReadOnlyList<TaskItem> Load() { string json = File.ReadAllText(path); List<TaskItem>? loaded; try { loaded = JsonSerializer.Deserialize<List<TaskItem>>(json, Options); } catch (JsonException e) { throw new StoreFormatException($"{path} is not valid task data", e); } // The text "null" is valid JSON but not a task list; an empty list is written []. return loaded ?? throw new StoreFormatException($"{path} is not valid task data"); } // Write to a temporary file first, so a failed write can't damage the last good save. public void Save(IEnumerable<TaskItem> tasks) { string temporary = path + ".tmp"; File.WriteAllText(temporary, JsonSerializer.Serialize(tasks, Options)); File.Move(temporary, path, overwrite: true); } } #nullable enable namespace TaskTracker; public record Report(int Open, int Done, int Overdue, IReadOnlyDictionary<Priority, int> OpenByPriority); public static class Reports { // Open tasks first, then soonest due, then highest priority; the id keeps ties stable. public static IEnumerable<TaskItem> Ordered(IEnumerable<TaskItem> tasks) { return tasks .OrderBy(task => task.Done) .ThenBy(task => task.Due) .ThenByDescending(task => task.Priority) .ThenBy(task => task.Id); } public static IEnumerable<TaskItem> Overdue(IEnumerable<TaskItem> tasks, DateOnly today) { return tasks.Where(task => !task.Done && task.Due < today); } public static Report Build(IReadOnlyCollection<TaskItem> tasks, DateOnly today) { var open = tasks.Where(task => !task.Done).ToList(); var byPriority = open.GroupBy(task => task.Priority).ToDictionary(group => group.Key, group => group.Count()); return new Report(open.Count, tasks.Count - open.Count, Overdue(tasks, today).Count(), byPriority); } } #nullable enable namespace TaskTracker; public interface IClock { DateOnly Today { get; } } public class SystemClock : IClock { public DateOnly Today => DateOnly.FromDateTime(DateTime.Now); } public class FixedClock : IClock { public DateOnly Today { get; } public FixedClock(DateOnly today) { Today = today; } }

Read Checks.cs and notice what it tests. The boundary cases come from the brief, and each failure message names the rule.

Break it on purpose

Each change below is a realistic slip. Make one at a time in the tabs above, press Run, and confirm that a check fails. Then undo it.

FileChangeWhat should fail
Tracker.cstrimmed.Length > MaxTitleLength to >=The 60-character title is refused
Tracker.cstasks.Max(task => task.Id) + 1 to tasks.Count + 1Ids continue after the highest loaded
Stores.csloaded ?? throw new StoreFormatException($"{path} is not valid task data") to loaded ?? new List<TaskItem>()Refuses saved data: null
Reports.cstask.Due < today to <=A task due today counts as overdue
Reports.csRemove !task.Done &&Finished tasks count as overdue
Reports.csThenByDescending to ThenByLow priority sorts first

The project's own automated tests apply these changes and more, on every run. If one of them ever stopped failing, that test would report a mutation that had survived.

The fake store

Tracker.Load handles failures, but a real disk rarely fails on command. FakeStore implements ITaskStore and can throw whatever a check asks for. Here's the idea at its smallest. Predict the result, then see how the tasks are protected.

A store that fails on command C#
#nullable enable

var book = new Book();
book.Load(new FakeStore(new List<string> { "kept" }));
Console.WriteLine(book.Titles.Count);

Console.WriteLine(book.Load(new FakeStore(null)));
Console.WriteLine(book.Titles[0]);

interface IStore
{
    List<string> Load();
}

class FakeStore(List<string>? saved) : IStore
{
    public List<string> Load() => saved ?? throw new IOException("disk");
}

class Book
{
    private readonly List<string> titles = new();

    public IReadOnlyList<string> Titles => titles;

    public string Load(IStore store)
    {
        List<string> loaded;
        try
        {
            loaded = store.Load();
        }
        catch (IOException e)
        {
            return $"failed: {e.Message}";
        }
        titles.Clear();
        titles.AddRange(loaded);
        return "loaded";
    }
}
Check your prediction
Text
1
failed: disk
kept

Round-trip checks

The most valuable storage check saves data with the real code, loads it back, and compares. Because records have value equality, comparing is one line. A list compares by reference, though, so use SequenceEqual.

What you save is what you get C#
#nullable enable

using System.Text.Json;

var original = new List<Item> { new(1, "Read"), new(2, "Write, then edit") };

string json = JsonSerializer.Serialize(original);
List<Item>? restored = JsonSerializer.Deserialize<List<Item>>(json);

Console.WriteLine(restored == original);
Console.WriteLine(restored!.SequenceEqual(original));

record Item(int Id, string Title);
Check your prediction
Text
False
True

The ! is safe here. This JSON was written a moment ago, so it can't be the literal null.

Your turn

Exercise

Test a rule table

The tracker's Overdue rule depends on three facts: whether the task is done, and whether it's due before, on or after today. Write a table-driven check with all six combinations for IsOverdue(DateOnly due, bool done, DateOnly today), then a correct IsOverdue. Print Overdue checks passed if nothing fails. Try changing < to <= to see a row fail.

When every check passes, it prints:

Text
Overdue checks passed
Your workspace C#
var today = new DateOnly(2026, 11, 2);
Console.WriteLine(today.AddDays(-1) < today);
Hint 1: the idea

Done can be true or false, and the date can be yesterday, today or tomorrow. Two times three gives your six rows, and only one row expects true.

Hint 2: a first step

Make an array of (int Offset, bool Done, bool Expected) tuples, and use today.AddDays(offset) in the loop to build each due date.

Show one solution
C#
var today = new DateOnly(2026, 11, 2);
var rows = new (int Offset, bool Done, bool Expected)[]
{
    (-1, false, true),
    (0, false, false),
    (1, false, false),
    (-1, true, false),
    (0, true, false),
    (1, true, false),
};

int failures = 0;
foreach (var (offset, done, expected) in rows)
{
    if (IsOverdue(today.AddDays(offset), done, today) != expected)
    {
        Console.WriteLine($"FAILED: offset {offset}, done {done}");
        failures++;
    }
}
if (failures == 0)
{
    Console.WriteLine("Overdue checks passed");
}

static bool IsOverdue(DateOnly due, bool done, DateOnly today) => !done && due < today;
Text
Overdue checks passed

The rows cover every combination of the two inputs: due yesterday, today and tomorrow, each both open and done. Offsets from today keep the table readable and make "due today" an exact case, which is the one an off-by-one mistake would break. A fixed today means the check gives the same answer on any day you run it.

Was this article helpful?

Your response is saved on this device.