A Dirty C++ Testing Trick

August 15, 2010

Say you need access to a private member when testing. In my current case, I haven't invented the machinery for state transitions, but I'm writing the OpenGL rendering based on our hero's state (this is for my Impossible Mission clone).

Boost often provides friend classes and template friends to do this, but this can be a lot of work. What I've done is made the member protected, then:

 struct TestableGuy : public Guy {
     inline State& state() { return state_; }

In my testing code:

       Guy g(Point(99,99), ts);
       reinterpret_cast<TestableGuy&>(g).state() = s;

I'm using reinterpret_cast<> to avoid needing to maintain constructors on TestableGuy as I add them or change them on Guy. Since no new data members or virtual functions were added, we can be assured that the classes have the same binary representation.

Tags: C++ fixme