Przejdź do głównej zawartości

Piotr's Less Obvious Advice on Google Mock: Mocking destructors

Can we verify that a mock object is properly destroyed? Of course! There is a couple of subtle differences between mocking regular functions and mocking destructors. Let's suppose we have a Grinder object that destroys any Piece object passed to its grind method:

void Grinder::grind(Piece * piece) {
  delete piece;

Furthermore, Grinder can accumulate a list of Pieces (actually, let it be a list of pointers to Pieces) for destruction that will take place when Grinder itself is destroyed. To add a Piece to the list, we define:

int Grinder::enqueue_piece(Piece * piece) {
  return list_of_pieces_.size();

Now, to keep the promise of destroying the queued pieces, Grinder's destructor is defined as follows:

Grinder::~Grinder() {
  for(list<Piece*>::iterator it = list_of_pieces_.begin(); it != list_of_pieces_.end(); it++) {
    delete *it;


But how can we mock the destructor of Piece so that we can verify that Grinder really destroys Pieces in both scenarios (on grind method call and on Grinder destruction)? Well, we can't really mock Piece's destructor itself, but we can use a workaround: it's enough to define MockPiece destructor so that it calls another function, such as destroy, that will be used as a signal for us that the destructor has been called.

class Piece {
  virtual ~Piece() {}

class MockPiece : public Piece {
  MOCK_METHOD0(destroy, void());
  virtual ~MockPiece() { destroy(); }

Now, a test like:

TEST(Grinder, CanGrindPiece) {
  MockPiece * piece = new MockPiece;
  Grinder grinder;

  EXPECT_CALL(*piece, destroy());


Will pass correctly (we know that grind method deletes the object passed as a pointer argument). But what about this test:

TEST(Grinder, CanGrindWhenDies) {

  MockPiece * p1 = new MockPiece;
  MockPiece * p2 = new MockPiece;
  MockPiece * p3 = new MockPiece;
  list<Piece*> list_of_pieces;

  Grinder grinder;

  EXPECT_CALL(*p1, destroy());
  EXPECT_CALL(*p2, destroy());
  EXPECT_CALL(*p3, destroy());


  //Grinder dies after this line

If you try out test example above with the correct implementation of Grinder's destructor, it will pass. But try to comment out the delete statement in Grinder's destructor and see what happens. Google Mock prints error messages like:

.//Grinder_test.cpp:34: ERROR: this mock object (used in test Grinder.CanGrindWhenDies) should be deleted but never is. Its address is @0x809d5e0.

but it still reports that the test itself passed! We would like to have Google Mock report test failure in this case, wouldn't we? The trouble is that Grinder dies when our test is already finished (when it goes out of TEST scope - it is an automatic object). The workaround here is to add another "helper" test that will verify our expectations after  the proper test has been finished. Let's do the following modification: move MockPieces p1, p2 and p3 from CanGrindWhenDies test to global scope. Then, let's add a short helper test:


That's it: this implementation of expectations and verification will yield correct results ("helper" test passing or failing) depending on whether Grinder's destructor is implemented correctly.

Exercise: try to move VerifyAndClearExpectations statements to CanGrindWhenDies test and see what happens when you run the test with correct and incorrect implementation of Grinder's destructor.


Popularne posty z tego bloga

Unit Testing code with IO file operations (in Python)

We may often come across a piece of code that was written without Unit Tests at all. In addition, the piece of code may be dealing with IO like file writing and reading, which makes it more difficult to Unit Test it when we are trying to refactor and modify. Let's suppose the code in question looks like this:

def writeInitialsToFile(filename, name, surname):
    initials = name[0] + '.' + surname[0] + '.'
    with open(filename, 'w') as file:

def readInitials(filename):
    initials = None
    with open(filename, 'r') as file:
        initials = file.readline()
    return initials

A straightforward and bad idea would be to write a couple of Unit Tests that make use of a real file and simply test the reading and writing. Is therea a better way to test this code?

First of all, we need a way to replace the real file with something else. For both reading and writing we will now have a couple of functions, one that expects a stream fo…

Piotr's Less Obvious Advice on Google Mock: State maintenance

Google Mock provides several ways to maintain state inside mock objects. One way of implementing state maintenance is with SaveArg. Consider the following example.

We have a class Configurator, which allows a caller to set and get values of a parameter:

class Configurator

    virtual ~Configurator() {}

    virtual void setParamX(int n) = 0;
    virtual int getParamX() = 0;

And we have a class Client that calls Configurator's methods and it also has a method incParamXBy, that can be used to increase the current value of paramX by a certain value.

class Client

    Client(Configurator & cfg);
    virtual ~Client() {}

    void setParamX(int n);
    void incParamXBy(int n);
    int getParamX();


    Configurator & _cfg;

incParamXBy internally calls setParamX and getParamX on Configurator:

void Client::incParamXBy(int n)
    _cfg.setParamX(_cfg.getParamX() + n);

Let's assume that the initial value of paramX is A and that we want to increase paramX by…

Piotr's Less Obvious Advice on Google Mock: Returning new objects from a mock

Google Mock provides a way to return newly created objects from a mock method. Suppose we have a  Generator class that is supposed to generate new objects when createNewRecord method is called:

class Generator
    virtual ~Generator() {}
    virtual Record * createNewRecord() = 0;

...and suppose we want to mock this class:

class MockGenerator : public Generator
    MOCK_METHOD0(createNewRecord, Record * ());

Suppose the caller class Client has run method defined as follows:

void Client::run()
    for(int i = 0; i < 3; i++)
        rec_tab[i] = gen.createNewRecord();

We want the mock to return a pointer to a new object each time createNewRecord is called. This is how we can express this in the test code:

TEST(ClientTest, CanRun)
    MockGenerator gen;
    Client c(gen);

    EXPECT_CALL(gen, createNewRecord())
                 //this is equivalent of returning new Record(1,2,3)