Solution 5: Poor Man's Mock Objects, Second Edition

The former example can be rewritten with a class especially designed for tracking occurences. The class handles setting default values and incrementing counter values based on a shared master object.

class PoorMockSecondEdition : public Interface
                            , public MockObject
{
    TrackingCounterMaster counter;

  public:

    TrackingCounterClient open_counter;
    TrackingCounterClient read_counter;
    TrackingCounterClient write_counter;
    TrackingCounterClient close_counter;

    PoorMockSecondEdition()
      : MockObject("MockObject")
      , counter("counter", this)
      , open_counter("open_counter", counter)
      , read_counter("read_counter", counter)
      , write_counter("write_counter", counter)
      , close_counter("close_counter", counter)
    {
    }

Then each method invocation updates its own tracking object by getting the current value from the master.

    virtual void open(const std::string &name )
    {
      open_counter++;
    }

Similar to all the other basic mock objects you set up the expected count for each object, call the object and verify it afterwards.

  Consumer consumer(&mock);
  mock.open_counter.setExpected(1);
  mock.read_counter.setExpected(4);
  mock.close_counter.setExpected(5);
  consumer.load();
  mock.verify();

poormock-se.cpp contains the complete source code.

Next: CppUnit Basics

Table of contents

 All Classes Namespaces Files Functions Variables Typedefs Friends Defines

Generated on Tue Jan 5 18:03:33 2010 for mockpp-tutorial by  doxygen 1.6.1