×

c# · level 3 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.