views:

132

answers:

4
+1  A: 

How about taking the existing functions, move the code inside into a new class and call the new methods from the existing functions and then override this class during tests?

Like so:

 static DBAccessClass dac = new DBAccessClass ();

 void origFunction() { dac.origFunction(); }

And in the test:

 dac = new DBAccessMockup();
Aaron Digulla
Yes, more or less 'pimpl', a reasonable option too.
lk
The biggest advantage of this is that you need only change one piece of code and you can even write tests for the DB methods.
Aaron Digulla
+1  A: 

You can try to override at the linker level. Have two different .cpp files that implement the functions in the header that describes the DB interface - one calling the real DB, one calling a fake interface. When you link for unit test, replace one with the other (Target Specific Variables in GNU make may help).

Arkadiy
A: 

You may also want to look at Michael Feathers' book Working Effectively with Legacy Code. Not only does he discuss exactly these types of problems, but the book includes numerous examples in C++ (in addition to Java, C, and C#). Feathers is also the original creator of CppUnit.

glaxaco
A: 
  1. Make file into class and override methods. [...]
  2. Wrap the whole source file with an #ifdef [...]

If possible, go with 1, as you will have a centralized way of referring to the database code (a class pointer instead of X functions). That means modularity, ease in replacing the implementation (with stubs or with another DB back-end) and more encapsulated code.

If you go with 2, consider replacing the implementation of the functions. That is, inside the original functions, engage the testing code (based on an if).

Your tested code is completely agnostic if running in a test environment or not, the performance loss is negligible (if(booleanFlagHere) is a negligible cost in most cases) and you don't have to modify the tested code at all).

utnapistim