c++unit-testingtddfactorycppunit

How do I unit test a factory?


I unit test my classes by giving all my classes an interface. These interfaces have in turn their own mocks.

But lets say I have the following:

class IData
{
  GetData()
}

class IOnScreenDataCalculator
{
  Calculate(IData)
}

class OnScreenData : IOnScreenData
{
  OnScreenData(PTR_T(IData), PTR_T(IOnScreenDataCalculator))

    enter code here

  GetOnScreenData()
}

Now lets say that I wish to have a number of factories for different types of data and calculators. How can I unit test these factories where my factories are as follows:

OnScreenBlueDataForWideScreenFactory
{
  PTR:T(IOnScreenData) Create()
  {
    PTR_T(Data) data = ptr_t(new BlueData());
    PTR_T(IOnScreenDataCalculator) calculator = ptr_t(new WideScreenDataCalculator());
    PTR_T(IOnScreenData) onScreenData = ptr_t(new WideScreenDataCalculator(data, calculator ));

    return onScreenData;
  }
}

Thanks for your help,

Barry.


Solution

  • I am not sure the code snippets are really c++, but the example should be something like this :

    class ExampleIface
    {
      public:
        virtual ~ExampleIface() {}
        virtual void a() = 0;
    };
    
    class Example1: public ExampleIface
    {
      public:
        virtual ~Example1() {}
        virtual void a()
        {
          // something
        }
    };
    
    class ExampleFactory
    {
      public :
        typedef ExampleIface * ExamplePtrType; // can be shared_ptr instead
    
        static ExamplePtrType Create( /*params?*/)
        {
          ExamplePtrType p( new Example1 );
          return p;
        }
    
      private:
        ExampleFactory();
        ~ExampleFactory();
    };
    

    and the unit test:

    void test_Create()
    {
      ExampleFactory::ExamplePtrType p = ExampleFactory::Create();
      Example1 *realType = dynamic_cast< Example1* >( p );
      TS_ASSERT( NULL != realType ); // if you use cxxtest
    }