Monday, April 23, 2012

A New Way to Test

In the previous project for Object-Oriented Programming, or "Brogramming", (since we always program with partners :) ) I was trying to conjure up new ways to get access to my private variables from cppunit tests.

The ugliest way is to use getters and setters to play with the variables you want to check and modify. Using getters and setters is typically frowned upon though, and there are much better ways to test your code, especially if you are only creating the getter and setter methods for testing purposes.

One of the ways that was conversed about in class was to make the test cppunit structs friends of the classes you want access to. This gives the cppunit tests access to all of the variables, and we can do our testing without the hassle of dealing with getters and setters. The problem with this is that we literally have to declare the test class or struct a friend in each class or struct we want access to, and I would argue that putting these friends in your classes can needlessly clutter source code, even it is only a few added lines.

I then got the wonderful idea of using macros to play with the private, public, and protected declarations within the classes, isolating the test file access from the body of the source code. The first option with this is to do something like the following:

//not the test file
#ifdef test_mode
    #define private public
#endif

//testfile
#define test_mode

This could be considered by some to be a little on the dangerous side, so at this point I introduce a tradeoff. In one hand, we could simply give anyone who defined "test_mode" access to all of the private variables in the class we are trying to test. In the other we could do something a little more complex like the following:

//not the test file
#ifdef test_mode
    #define private protected
#endif

//testfile
#define test_mode

So instead of simply making all of the private variables public, we make them protected. Why? Well, in this case any class which is a child of all the classes in the source file being tested will have access to all of the previously private variables. The idea is that now we can simply declare the test class a child of the class(es) we want to test and test away!

1 comment: