My Introduction to Unit Tests

In an attempt to level up my code, I felt it important to jump into unit tests.

I dabble mainly in python and c/c++. In Python I made use of the native unitest framework and in my c++ example I made use of googletest

The C++ version was more difficult to set up, a good project structure and understanding of Cmake will help. Once I had overcome this, then the concepts were mostly the same.

The Python Version

class MyTestCase(unittest.TestCase):
    def test_list_int(self):
        data = [1, 2, 3]
        result = sum(data)
        self.assertEqual(result, 6)

if __name__ == '__main__':
    unittest.main()

We can see that the test case is initiated as a subclass, our test functions go in here. We call the sum() function from the main codebase to assert that the value is equal to 6, our expected result.

C++ Version

#include "gtest/gtest.h"

int main(int argc, char **argv) {
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

A little more complicated, this is the main function that calls each test. The actual tests are stored in separate .cpp files

#include "gtest/gtest.h"
#include "calc.h"

TEST(add_test, Add) {
    ASSERT_EQ(2, add(1, 1));
    ASSERT_EQ(20, add(10, 10));
    ASSERT_EQ(20, add(15, 5));
}

Along with the actual function being tested in the calc.h and calc.cpp file which lives in the main src folder within the project.

#include "calc.h"

int add(int op1, int op2) {
    return op1 + op2;
}

The C++ example, does not use a class in this case, but I am sure that there is a way to set up the tests in this respect. My current understanding is that the googletest library exposes the a set of macros in which the tests are structured around.

Instead of our test case having a class name, it is within the definition of the TEST() macro.

ASSERT_EQ checks the value of our add function, which is defined in the src folder of the project.

The main() function at the top of the c++ example, serves as the calling function for all the tests, similar to the way that in the Python version unitest.main() works.

The issue that I found with the c++ testing was actually getting the whole thing to link and compile properly using Cmake. When configured correctly, the Cmake project generates two binaries. One the compiled application and the other, the compiled tests, the tests are then run as if they are their own application.

Over all I feel I have only just scratched the surface of this topic and look forward to exploring it further in my projects.