c# · level 3 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A checks one small piece, every time you run it.
A unit test runs one small piece of code with known inputs and checks the answer. Tests catch a mistake the moment you make it, and let you change code without fear. Testing tools exist, but the core is tiny: an , a check that complains loudly when something is wrong.
Write AssertEqual(expected, actual, name) once and call it for every case. Make it generic, and compare with Equals, which works for any T. Test every too: the odd inputs at the limits, like zero, an empty list or a 100 percent discount.
using System;
int passed = 0;
int failed = 0;
AssertEqual(90m, AfterDiscount(100m, 10), "ten percent off");
AssertEqual(0m, AfterDiscount(0m, 50), "free stays free");
AssertEqual(100m, AfterDiscount(100m, 0), "no discount");
AssertEqual(0m, AfterDiscount(100m, 100), "everything off");
Console.WriteLine($"{passed} passed, {failed} failed");
decimal AfterDiscount(decimal price, int percent) => price - price * percent / 100;
void AssertEqual<T>(T expected, T actual, string name)
{
if (Equals(expected, actual))
{
passed++;
Console.WriteLine($"PASS {name}");
return;
}
failed++;
Console.WriteLine($"FAIL {name}: expected {expected}, got {actual}");
} Equals(a, b) is a built-in method every type understands, which is why the generic version can use it.
guess first
Two tests for one method. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
AssertEqual("Ana", Capitalise("ana"), "lower case");
AssertEqual("Ana", Capitalise("ANA"), "upper case");
string Capitalise(string name) => char.ToUpper(name[0]) + name.Substring(1);
void AssertEqual<T>(T expected, T actual, string name)
{
if (Equals(expected, actual))
{
Console.WriteLine($"PASS {name}");
return;
}
Console.WriteLine($"FAIL {name}: expected {expected}, got {actual}");
}
your turn
Your turn. Test that bad prices are refused.
On line 4, choose a price that should be refused, and name the test. Then, on line 20, write the exception type a refused price throws.
output
press run to see what happens
fix it
The test helper will not compile. Can you fix it?
output
press run to see what happens
- C# says
==cannot be used on two values of typeT, on line 11. Tcould be any type, and not every type has==. Every type does haveEquals.- Change the test on line 11 to
Equals(expected, actual), then run.
nailed it
you test your code like a professional. :D
- A unit test checks one small piece with known inputs.
- Compare generic values with
Equals, not==. - Test the edge cases, and test that bad input throws.
new words in your collection
- unit test
- assertion
- edge case
This lesson isn’t saved. A free account remembers every lesson you finish.