Unit Testing

​The gist of testing

  • Programming introduces bugs

  • Testing helps find bugs

  • Debugging finds and fixes bugs

  • Many types of testing: different levels of abstraction and methodologies

  • Testing measures code correctness/quality

    • You cannot test correctness/quality into code

  • You usually can’t test all possible inputs or even all code paths

    • Aim to get “enough” code coverage. “Enough” is about 85% - 90%.

    • Quality over quantity

  • TDD: Write tests first, then write code to pass the tests

    • Tests are formal expressions of the requirements

Unit Testing

  • Unit := “smallest testable part of software”

    • Usually few inputs and a single output • Unit Test: Test a single unit (in isolation)

  • Goal: validate that each unit is correct

    • If units are correct, they can be (correctly) combined to solve problems

  • Typically automated • Many frameworks exist. Mimir uses Google Test for C++

  • TDD: write the tests before you write the function

// compute the greatest common divisor
int gcd(int a, int b);
// test
int a = 45, b = 63;
int expected = 9;
int actual = gcd(a, b);
if (actual != expected) {
    cout << “FAIL” << endl;
    cout << “ expected: ” << expected << endl;
    cout << “ got: ” << actual << endl;
} else {
    cout << “PASS” << endl;
}

Last updated

Was this helpful?