...

/

Creating the Most Basic Unit Test for CTest

Creating the Most Basic Unit Test for CTest

Let's learn how to add a simple test.

We'll cover the following...

Writing unit tests is technically possible without any kind of framework. All we have to do is create an instance of the class we want to test, execute one of its methods, and check if the new state or value returned meets our expectations. Then, we report the result and delete the object under test.

Example

Let's try it out. We'll use the following structure:

Press + to interact

Starting from main.cpp, we can see it will use a Calc class, as illustrated in the following code snippet:

Press + to interact
#include <iostream>
#include "calc.h"
using namespace std;
int main() {
Calc c;
cout << "2 + 2 = " << c.Sum(2, 2) << endl;
cout << "3 * 3 = " << c.Multiply(3, 3) << endl;
}

Nothing too fancy—main.cpp simply includes the calc.h header and calls two methods of the Calc object. Let's quickly glance at the interface of Calc, our SUT, as follows:

Press + to interact
#pragma once
class Calc {
public:
int Sum(int a, int b);
int Multiply(int a, int b);
};

The interface is as simple as possible. We're using #pragma once here—it works exactly like commonly seen preprocessors, including guards, and is understood by almost all modern compilers despite not being part of the official standard. Let's see the class implementation as follows:

Press + to interact
#include "calc.h"
int Calc::Sum(int a, int b) {
return a + b;
}
int Calc::Multiply(int a, int b) {
return a * a; // a mistake!
}

Uh-oh! We introduced a mistake! Multiply is ignoring the b argument and returns a squared instead. That should be detected by ...