I have a unit test class Tester
; I want it to access private fields of a Working
class.
class Working {
// ...
private:
Try very hard to test all your private code using your public interface. Not only is it less work initially, but when you change the implementation there is much higher chance that the unit tests will still work.
That said, sometime you just need to poke at the innards to get good test coverage. In that case I use an idiom I call expose. There is a joke in there if you think about it.
Foo class that needs to be tested
class Foo
{
public:
// everyone is on their honor to only use Test for unit testing.
// Technically someone could use this for other purposes, but if you have
// coders purposely doing bad thing you have bigger problems.
class Test;
void baz( void );
private:
int m_int;
void bar( void );
};
foo_exposed.h is only available to unit test code.
class Foo::Test : public Foo
{
public:
// NOTE baz isn't listed
// also note that I don't need to duplicate the
// types / signatures of the private data. I just
// need to use the name which is fairly minimal.
// When i do this I don't list every private variable here.
// I only add them as I need them in an actual unit test, YAGNI.
using Foo::m_int;
using Foo::bar;
};
// yes I'm purposely const smashing here.
// The truth is sometimes you need to get around const
// just like you need to get around private
inline Foo::Test& expose( const Foo& foo )
{
return * reinterpret_cast(
&const_cast( foo )
);
}
How it would be used in unit test code
#include "foo_exposed.hpp"
void test_case()
{
const Foo foo;
// dangerous as hell, but this is a unit test, we do crazy things
expose(foo).m_int = 20;
expose(foo).baz();
}