A dozen near-identical checks hide what they test. Today's checkpoint keeps cases as data, in a table: one row for each input and its expected answer, with one loop that runs them all. Adding a case is one line, and gaps in your thinking become easier to see. Test frameworks call this a theory or a parameterized test.
A table of cases
A tuple or small record holds each row. The loop's failure message includes the row, so a failure tells you exactly what went wrong. This run has one bad expectation in it, to show that the checker works.
var cases = new (string Input, bool Expected)[]
{
("a@b.com", true),
("no-at", false),
("@b.com", false),
("a@", true),
};
int failures = 0;
foreach (var (input, expected) in cases)
{
bool actual = LooksLikeEmail(input);
if (actual != expected)
{
Console.WriteLine($"FAILED: {input}: expected {expected}, got {actual}");
failures++;
}
}
Console.WriteLine($"{failures} failed of {cases.Length}");
static bool LooksLikeEmail(string text)
{
int at = text.IndexOf('@');
return at > 0 && at < text.Length - 1;
}Check your prediction
FAILED: a@: expected True, got False
1 failed of 4A reusable, generic runner
One generic method can run any table. It takes the function under test as a delegate, and everything you've learned this week comes together here. EqualityComparer<T>.Default compares two values of any type correctly.
int failures = 0;
Table("Length", (string s) => s.Length, ("", 0), ("abc", 3));
Table("Is even", (int n) => n % 2 == 0, (2, true), (3, false), (0, true));
Table("Broken double", (int n) => n + n + 1, (1, 2));
Console.WriteLine($"{failures} failed");
void Table<TIn, TOut>(string name, Func<TIn, TOut> function, params (TIn Input, TOut Expected)[] rows)
{
foreach (var (input, expected) in rows)
{
TOut actual = function(input);
if (!EqualityComparer<TOut>.Default.Equals(actual, expected))
{
Console.WriteLine($"FAILED: {name}({input}): expected {expected}, got {actual}");
failures++;
}
}
}Check your prediction
FAILED: Broken double(1): expected 2, got 3
1 failedWould your tests notice?
A passing check proves little if it would also pass with broken code. Mutation testing tests the tests: change the code on purpose, and confirm that a check fails. If nothing fails, you've found a gap. This site's own course checks do that, running the projects with deliberate bugs, and that's how a real gap was found in the tracker's checks while this course was being written: nothing noticed if Load set the next id to Count + 1, which reuses an id if saved ids have gaps.
Fix it: Checks that can't fail
This table of cases has a wrong expectation in it, on purpose. Predict the output, then run it.
var cases = new[] { (Input: 2, Expected: 4), (Input: 3, Expected: 10) };
int failures = 0;
foreach (var (input, expected) in cases)
{
int actual = input * input;
if (actual != expected)
{
Console.WriteLine($"FAILED: {input} gave {actual}, expected {expected}");
}
}
Console.WriteLine(failures == 0 ? "All checks passed" : $"{failures} failed");Check your prediction
FAILED: 3 gave 9, expected 10
All checks passedThe runner reports the failure but never counts it, so its verdict is always a pass. Anyone reading only the last line, such as an automated build, sees success. Fix it.
Fix it
Count each failure where it's reported:
var cases = new[] { (Input: 2, Expected: 4), (Input: 3, Expected: 10) };
int failures = 0;
foreach (var (input, expected) in cases)
{
int actual = input * input;
if (actual != expected)
{
Console.WriteLine($"FAILED: {input} gave {actual}, expected {expected}");
failures++;
}
}
Console.WriteLine(failures == 0 ? "All checks passed" : $"{failures} failed");FAILED: 3 gave 9, expected 10
1 failedPlanting a wrong expectation, as this table does, is the quickest way to check that a runner can fail at all. Do it once whenever you write a new runner, then correct the case.
Build it yourself
Test a discount calculator, then break it
Discount(int quantity, bool member) returns a percentage: 0 below 10 items, 5 from 10 to 49 items, 10 from 50 items, plus 5 more for members. A quantity below 0 throws ArgumentOutOfRangeException.
Write a table with enough rows to catch these bugs, then try each one: quantity < 10 changed to quantity <= 10; < 50 changed to <= 50; and the member bonus removed. Add one more check for the exception. Print All checks passed when everything is correct.
When every check passes, it prints:
All checks passedConsole.WriteLine(Discount(10, false));
static int Discount(int quantity, bool member)
{
ArgumentOutOfRangeException.ThrowIfNegative(quantity);
int percent = quantity switch
{
< 10 => 0,
< 50 => 5,
_ => 10,
};
return member ? percent + 5 : percent;
}Hint 1: the idea
Each boundary needs a row on both sides: 9 and 10, 49 and 50. Don't forget 0, and rows with member set to true.
Hint 2: a first step
Start with an array of (int Quantity, bool Member, int Expected) tuples holding one row, and a loop that prints any mismatch. Then add a row for each boundary.
Show one solution
var cases = new (int Quantity, bool Member, int Expected)[]
{
(0, false, 0),
(9, false, 0),
(10, false, 5),
(49, false, 5),
(50, false, 10),
(9, true, 5),
(10, true, 10),
(50, true, 15),
};
int failures = 0;
foreach (var (quantity, member, expected) in cases)
{
int actual = Discount(quantity, member);
if (actual != expected)
{
Console.WriteLine($"FAILED: {quantity}, {member}: expected {expected}, got {actual}");
failures++;
}
}
try
{
Discount(-1, false);
Console.WriteLine("FAILED: -1 should throw");
failures++;
}
catch (ArgumentOutOfRangeException)
{
}
if (failures == 0)
{
Console.WriteLine("All checks passed");
}
static int Discount(int quantity, bool member)
{
ArgumentOutOfRangeException.ThrowIfNegative(quantity);
int percent = quantity switch
{
< 10 => 0,
< 50 => 5,
_ => 10,
};
return member ? percent + 5 : percent;
}All checks passedThe cases sit on both sides of every boundary (9 and 10, 49 and 50), because that's where < and <= mistakes hide. The member cases check that the extra 5 is added at every tier, and a separate check proves that a negative quantity is refused rather than given a discount. Each failure is counted where it's printed, so the final verdict can't say "passed" after a failure.
Did you see every bug get caught? If a mutation survived, add the row that would have caught it, then try the bug again.
Completion is saved in this browser only. It does not measure mastery.