Given the following code example which represents a simplification of a much larger project:
class IEaterOfCake
{
public:
virtual void EatCake() = 0;
};
class CakeMaker
{
public:
CakeMaker(IEaterOfCake & e) : mCakeEater(e) {}
void MakeCake() { mCakeEater.EatCake(); }
protected:
IEaterOfCake & mCakeEater;
};
class HungryMan : public IEaterOfCake
{
public:
HungryMan() : mCakeMaker(*this) {}
void HaveLunch() { mCakeMaker.MakeCake(); }
virtual void EatCake() override {/* mmmm cake */};
private:
CakeMaker mCakeMaker;
};
int main()
{
HungryMan m;
m.HaveLunch();
}
I can nicely unit test CakeMaker with a test like:
TEST(sometest)
{
class TestEater : public IEaterOfCake
{
virtual void EatCake() override {/* test cake is yummy */};
} t;
CakeMaker cm(t);
cm.MakeCake();
}
Now, I would like to test HungryMan with a mock CakeMaker. It is too complex to try test HunrgyMan and CakeMaker as a single unit. In practice HungryMan has several internal classes feeding into it in a similar way. The number of possibilities goes up exponentially!
Dependency injection of a CakeMaker (or interface to) would be ideal, but the hope was to hide them inside the HungryMan class. And I am not sure how to make sure references to teh dependencies would be initialised at construction, as those dependencies also need to reference the Hungry man . Note that ‘new’ cannot be used in this project, dynamic allocation is not allowed.
I am after suggestions on how to better structure this project so that HungyMan can be unit tested with a mock/test implementation. Currently I conditionally compile in a different type for mCakeMaker (MockCakeMaker). But I still have the issue where mCakeMaker is private and inaccessible to manipulate for testing.
I hope I explained OK, I struggled a bit!