Skip to content

Unit Testing

S. V. Paulauskas edited this page Feb 24, 2017 · 1 revision

#Introduction Unit tests test functions. Functions have the same definition as in mathematics : F(X) = Y. The unit test will check to make sure that this equation always holds true.

#Example Consider a function that adds two numbers:

double Add (const double &a, const double &b) {
    return a + b;
}

We would like to test that we always return the proper value. A test may look like the following

TEST(Add) {
    double a = 4.;
    double b = 5.;
    CHECK_EQUAL(a+b, Add(a,b));
}

What we would like to do is make sure that we have error handling in all of the functions. We can modify the above example to be this

double AddPositiveNumbers (const double &a, const double &b) {
    return a + b;
}

TEST(AddPositiveNumbers) {
    double a = 4.;
    double b = -5.;
    CHECK_THROW(AddPositiveNumbers(a,b), invalid_argument);
}

What would be the result of this test? How could we modify the function to pass the test?

Clone this wiki locally