Friday, December 20, 2013

Code Kata: A simple text-based calendar

In this Kata we want to properly display a simple calendar view of a given month. Let's start with an example. A proper output of our program for the input data of "December, 2013" would be:

Mo Tu We Th Fr Sa Su
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

Points to consider:
  • how many times we need to make a call to time-date functions?
  • try to minimize the number of these calls
  • try to separate program logic from presentation as much as you can

Tuesday, August 6, 2013

Code Kata: A rover

Another game-like exercise. A rover moves over a board with X and Y dimensions. Some places on the board are filled with stones and this is where the rover cannot move onto. Your task is to implement the rover and the board with the following requirements and restrictions:
  • the rover understands your commands (e.g. from command line) of the form:
    • forward - moves one step forward
    • left, right - makes 90 degrees turn left or right
  • if the rover gets the forward command and there is a stone in front of it, it just ignores it; you can optionally print a message to signal that
  • the rover does not have the knowledge of the terrain - it keeps a reference to a board [object] which actually knows where the stones are and tells the rover whether a given move is possible or not
  • the rover should not be allowed to move outside of the board
Although it will probably be fun to test this with command line, you are encouraged to use TDD as you go.

Tuesday, May 28, 2013

Bugs on a board - modern concurrency in Clojure

[ Inspired by Rick Hickey's Ant Colony Simulation ]
Having said before that Clojure is great, I feel obliged to provide a concrete example of a concurrent Clojure program. We will implement a simulation of N bugs walking randomly on an X x Y board. If two bugs walk onto the same cell, they both vanish. Let's start!

The board has dimensions specified as follows:

(def dimx 50)
(def dimy 50)

A bug performs one step from the current cell by randomly altering its (x,y) coordinates. Each coordinate is incremented or decremented by 1, or it stays the same.

(defn random-step [n]
  (let [step (rand-int 3)]
    (cond (= step 2) (dec n)
      (= step 1) (inc n)
      (= step 0) n)))

Next location for a bug will be randomly generated, unless a bug is at a border. In that case, it immediately jumps in the opposite direction.

(defn next-loc [loc]
(let [x (loc 0) y (loc 1)
      newx (cond (= x (dec dimx)) (dec x)
                 (= x 0) (inc x)
                 :else (random-step x))
      newy (cond (= y (dec dimy)) (dec y)
                 (= y 0) (inc y)
                 :else (random-step y))]
   [newx newy]))

Unique initial locations for bugs are generated at the start using this function:

(defn initial-locs [locs numof]
(if (= numof 0) locs
  (let [x (rand-int dimx) y (rand-int dimy)]
    (if (not-any? (fn [loc] (and (= x (loc 0)) (= y (loc 1)))) locs)
      (initial-locs (conj locs [x y]) (dec numof))
      (initial-locs locs numof)))))

We will initially have 20 bugs at 20 different locations:

(def init-locs (initial-locs [] 20))

Our simulated world will be a hashtable of agents (later we will see that the bugs are agents).

(defn init-world [w agent-list]
  (if (empty? agent-list) w
    (init-world (assoc w @(first agent-list) (first agent-list)) (rest agent-list))))

We create a list of bugs (agents) and  the world:

(def bugs (map #(agent %) init-locs))
(def world (atom (init-world {} bugs)))

We need a function that updates the world, given the world, old bug location, new bug location and bug alias. The function will also detect if the moving bug ends up at a cell occupied by another bug - in this case both need to be removed from the world.

(defn upd-world [world-map old-loc new-loc agent-alias]
  (= nil (world-map old-loc)) world-map
  (or (identical? agent-alias (world-map new-loc))
      (= nil (world-map new-loc)))
    (let [foo (dissoc world-map old-loc)]
      (assoc foo new-loc agent-alias))
    (let [foo (dissoc world-map old-loc)]
      (dissoc foo new-loc))))

We also need a function that directs the crawl of a bug. It will update the world upon each step.

(defn crawl [loc]
(if (= nil (@world loc)) loc
    (Thread/sleep 50)
    (send *agent* crawl)
    (let [newloc (next-loc loc)]
      (swap! world upd-world loc newloc *agent*)

Now we need some GUI stuff. Bugs will be represented as squares. Let's define bug size in pixels.

(def bugsize 5)

Import some useful GUI components:

(import [javax.swing JPanel JFrame])

(import [java.awt Color Dimension])

'Now the function for creating the frame:

(defn create-frame [panel]
(let [frame (JFrame.)]
(doto frame
  (.add panel)
  (.setVisible true)

And the main function for rendering the world:

(defn render [g]
  (.setColor g Color/white)
  (.fillRect g 0 0 (* bugsize dimx) (* bugsize dimy))
  (.setColor g Color/black)
  (doseq [k (vec (keys @world))]
    (if (@world k) (.fillRect g (* bugsize (k 0)) (* bugsize (k 1))
      bugsize bugsize)))))

One more GUI function:

(defn create-panel []
(let [panel (proxy [JPanel] []
  (paint [g]
    (render g)))]
(doto panel
  (.setPreferredSize (Dimension. (* bugsize dimx) (* bugsize dimy))))))

And we are really close - just initialize the GUI:

(def panel (create-panel))
(def frame (create-frame panel))

Define the animation agent that will repaint the frame periodically:

(def anim (agent nil))
(defn animate [x]
(when (> (count @world) 1)
    (Thread/sleep 10)
  (send-off *agent* animate)
  (.repaint panel)
  (.validate panel)))
(send-off anim animate)

And send the crawl function to all the bugs:

(dorun (map #(send-off % crawl) bugs))

That's it! Do Copy&Paste, remove my comments, download the latest Clojure jar from and start it:

java -jar clojure.jar

And from the Clojure REPL load the file containing the program:

(load-file 'bugs.clj')

This program is 96 lines long, including some empty newlines. This is an example of the expressive power of Clojure. It doesn't contain any locking, mutexes or semaphore handling code. All thread coordination is implemented using STM. So, comparing it to what it would take to implement the same thing in one of the more popular languages, what do you say?

Friday, May 24, 2013

Code Kata: shopping list search

We have a list of, let's say, goods we bought at a shop (or you can imagine any other list that you like):

|        Name        |      Quantity      |       Price      |
|        Beer          |           10          |        30            |
|       Pickles        |           1           |        12            |
|     Red beans    |            2           |        22            |

The task is to write a piece of code that will search through the list and will display each row that matches search criteria. Too simple? Maybe. But consider these additional hints:
  • search criteria may not be exact. The string "bean" might match "Red beans"
  • we may even be searching for any of a few items: rows one and three will both match if our search criteria are "any of 'beer', 'bean' ".
I recommend that you start this kata with an exact search for one item and then gradually move towards the "like/contains" criteria and to "any of" criteria and that you observe the impact these changes will have on your unit tests (needless to say, this should all be done using TDD).

Monday, May 6, 2013

Do I really have to call super(...).__init__ in Python?

Yes. But, if you prefer a longer answer:

Class B inherits from class A. When implementing B's __init__ function, we may call A's init by writing:

super(B, self).__init__(arguments of A's __init__)

Is it really necessary? After all, in C++ or Java the constructor of base class is called automatically, so shouldn't it be called automatically in Python as well?

The point is that __init__ is not a constructor. Python objects are constructed with __new__. __init__ is used to initialize an object with concrete values, either defaults or passed as __init__'s parameters.

Need more details? Read Python docs at

Thursday, April 18, 2013

Code Kata: text game from 1982

The goal is to implement a text-based game in which the player walks through dungeons in order to accomplish a task. The basic characteristics of an implementation are as follows:
  • the game generates random dungeons as a group of ROOMS and PATHS that join the ROOMS
  • the generation does not leave unreachable ROOMS
  • the user is presented with the information about the ROOM  they are in and the ROOMS reachable directly from the current ROOM
  • the user can move from the current ROOM to the directly reachable ROOMS by entering a command
This may seem very boring at first, but let's add some delighters:
  1. We do all of the implementation using "TDD, as if you meant it", of course
  2. Initially, the goal may be simply to get to a given ROOM
  3. Then, we may start adding attributes to ROOMS; a possible attribute is something that the user can collect, such as diamonds; N diamonds are placed in the dungeon and the game is finished when the user collects all of them; additional attributes can be used to describe the look a ROOM
  4. When that's done, we can refactor our implementation so that we do not use IF statements
  5. When that's done, we can refactor our implementation so that we do not use for/while loops
  6. We can work on the implementation a little bit more to get rid of excessive tabs (let's allow only up to two tabs in the body of a function, per Robert Martin's suggestion)
  7. We can get better by limiting the number of lines of a function (how about < 5 lines per function?)
  8. I'm guessing you did all of this with classes and objects; how would you do it with pure functions and no objects?

Tuesday, April 9, 2013

Python profiling for beginners

def bar(i):
    return i*i

def foo():
    for i in range(0,1000000):

Let's try to use these two silly functions to do a profiling exercise.

First of all, we need to import cProfile. And then call:'foo()')

Output (from my laptop):
         1000004 function calls in 3.564 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    1.926    1.926    3.564    3.564 <pyshell#11>:1(foo)
  1000000    1.638    0.000    1.638    0.000 <pyshell#9>:1(bar)
        1    0.000    0.000    3.564    3.564 <string>:1(<module>)
        1    0.000    0.000    3.564    3.564 {built-in method exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

At the first glance, it may look criptic, but: the total time is the time spent in a function excluding the time spent in callees. The cummulative time is the time spent in a function including the time spent in callees. Therefore, these two times are equal for bar function. ncalls and percall are self-explanatory.

But we can go further. I highly recommend trying out a GUI application that can read the cProfile output, such as RunSnakeRun from For this simple case it'd be useless, but for much more complex call tree, it is of great help.

In order to use it, we need to run cProfile giving it the dump file name as the second argument:'foo()', 'dump.txt')

Tuesday, March 26, 2013

SuperFib - an example of using lexical closure in Python

This story begins with simple implementation of a function that calculates Fibonacci numbers.

def fib(n):
    return 1 if n == 1 or n == 2 else fib(n-1) + fib(n-2)

Assuming that we are using 1-based indices, we can run a couple of tests and see that it works. Of course, fib(35) takes some time to calculate - about 15 seconds on my laptop.

Now, if you don't know what lexical closure is, I recommend reading about it on Wikipedia) before going further. Let's try to cache the results, but also be better than using conventional memoization - not only will we cache the final result of each call, but also intermediate results.

def fib():
    _dict = dict()
    def inner(n):

        nonlocal _dict
        if n == 1 or n == 2:
            return 1
                return _dict[n]
            except KeyError:
                _dict[n] = inner(n-1) + inner(n-2)
                return _dict[n]
    return inner

f = fib()
f(1000) returns instantly, with:

However, if I call f(1500) without calling f(1000) first, the calculation will not finish and my interpreter will crash or at least restart because of stack evaluation overflow.

But if I ran f(1000) and then f(1500) and then f(2000) and so on and so forth, advancing by 500 each time, I can very quickly get to quite far elements of Fibonacci sequence. Calculating 10 000th element is quick and easy, compared to conventional approach. We can quickly get to the point where printing the numbers to the console takes more time than actually calculating them.

Friday, March 22, 2013

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 for reading or writing and the other that creates the stream and calls the corresponding reading or writing function:

def readInitialsFromFileStream(fileStream):
    return fileStream.readline()

def readInitialsFromFile(filename):
    initials = None
    with open(filename, 'r') as fileStream:
        initials = readInitialsFromFileStream(fileStream)
    return initials

def writeInitialsToFileStream(fileStream, name, surname):
    initials = name[0] + '.' + surname[0] + '.'

def writeInitialsToFile(filename, name, surname):
    with open(filename, 'w') as fileStream:
        writeInitialsToFileStream(fileStream, name, surname)

Now, we can test at least the pair: readInitialsFromFileStream and writeInitialsToFileStream. In order to test these functions, we don't even need to create a file in the file system - we can just pass something that has similar characteristic, but is not a real file: io.StringIO.

A quasi - Unit Test piece (without the full unittest.TestCase class, to shorten things a bit) would look like this:

testStream = io.StringIO()
assert('T.M.', readInitialsFromFileStream(testStream))

testStream = io.StringIO()
writeInitialsToFileStream(testStream, 'Thomas', 'Mann')
assert('T.M.', testStream.readline())

Why is it better than using a real file? Some of the reasons (probably not all) are:
  • unit tests should work flawlessly regardless of the environment; when using real file, we may have different permissions depending on the computer and operating system where the tests are run
  • some tests (although this was not necessarily clear from the example) may require that the file has certain name or even certain content - otherwise they'll fail; by using a real file with pre-set name and content we are creating an unnecessary dependency that may impact the maintainability and, in the long run, usefullness of the tests
  • in order to avoid using a real file we had to separate the creation of a stream from writing to / reading from the stream; this forced us to make a first step towards fulfilling the Single Responsibility Principle

Sunday, March 17, 2013

Long if-else statement without if (in Python)

Let's suppose we find ourselves in a situation where we have no other option than to write a lengthy if-else statement (definitely not something that would make cleaner by polimorphism).

def inevitable_long_if (n):
    if n == 0:
    elif n == 1:
    elif n == 2:

Can we re-write it so that we do not use IFs?

import collections
import functools

d = collections.defaultdict(lambda : functools.partial(print, 'Manu-manu'))
d[0] = functools.partial(print, 'Zero')
d[1] = functools.partial(print, 'One')
d[2] = functools.partial(print, 'Two')

Now, let's call some to see how it works:

d[0]()  ==>  Zero
d[1]()  ==>  One
d[2]()  ==>  Two
d[7]()  ==> Manu-manu

The first version is 9 lines long, the second one (without imports) is 4 lines long. To me, the second version is also much more readable, but you decide.

Monday, March 4, 2013

Code Kata: Eating habits and Markov chains

The Wikipedia entry:
contains nice and clear explanation of the idea of Markov chains. Based on the paragraph about eating habits, we can form an interesting coding exercise:
  • A person eats lunch every day
  • We form a set of rules similar to the one presented in Wikipedia - one part of the exercise is how to represent these rules in a program. What would be the convenient way to represent this internally and how would you translate a possible textual representation (such as one entered from standard input) into the internal format? Would the two format be quite similar or quite different from each other?
  • We run a simulation for a number of days - say, 365 days - and we get statistical distribution of the number of each type of meals that would be eaten
Does it seem like a long program to write? My initial solution in Python was 23 lines long and then refined solution took just 14 lines.

Wednesday, February 27, 2013

Code Kata: Recently opened files

Kata #2: Recently opened files
Implement a container that has the well known functionality of "Recently opened files" that you know from various applications you use:
  • the container must be able to list file paths that it stores
  • if file A is opened and right after that we ask the container to list the file paths it stores, the path to file A will be listed as the first one
  • the number of stored file paths is limited; when the limit is exceeded the container forgets least recently used file path
  • in the list of recently open files, each file path can appear once and only once

Tuesday, February 26, 2013

Code Kata: Vending Machine

Kata #1: Vending Machine

Your task is to implement a piece of software for a vending machine that sells sweets. The machine accepts coins and must be capable of returning change. It is up to you to decide on how inserted coins and change that is given out are represented. Consider the following variations of this exercise:
  • Simplification: you have an unlimited number of coins of every kind
  • Realistic: the machine is loaded with coins at the beginning and you have a limit on the number of coins of every kind
  • More realistic: the machine adds the inserted coins to respective coin slots and uses them to serve further transactions
  • Even more realistic: the machine tries to optimize the way of giving out coins - if there is danger of giving out too many coins of kind A, and there are is surplus of coins of kind B, then more of B coins are used to produce change
  • Futuristic: the machine asks you to provide it with coins that would help it return the proper change
How would your implementation of vending machine react if the amount of money inserted were less than the price of the chosen chocolate snack?

Monday, February 25, 2013

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 B each time we call incParamXBy. Our expectation is that if incParamXBy is called for the first time, it will result in calling cfg.setParamX(A+B).
  • second call of incParamXBy(B) will result in calling cfg.setPAramX(A + 2*B)
  • third call: cfg.setPAramX(A + 3*B), and so on...

Interaction between Client and Configurator in this case is such that Client relies on Configurator (issues getParamX()) in order to correctly calculate the parameter for next setParamX() call. If we want to test Client object, we need a MockConfigurator that is able to remember its current value of the parameter we are increasing:

class MockConfigurator : public Configurator

    int paramX;
    int * paramX_ptr;

        paramX = 0;
        paramX_ptr = &paramX;
    MOCK_METHOD1(setParamX, void(int n));
    MOCK_METHOD0(getParamX, int());

MockConfigurator has a public member paramX. We will use paramX to store current value of the parameter. We could have put paramX outside of MockConfigurator, in the test code, but I think it makes more sense to bind the parameter with the object.

And now the test:

MockConfigurator cfg;
Client client(cfg);

int inc_value = 10;

//getParamX will be called a number of times.
//If it is called, we will return the value pointed to by paramX_ptr.
//Returning with ReturnPointee is necessary, since we need to have
//the actual (updated) value each time the method is called.

EXPECT_CALL(cfg, getParamX())

//SaveArg stores the 0th parameter of the call in the value pointed to by paramX_ptr (paramX)
//expectation 3
EXPECT_CALL(cfg, setParamX(cfg.paramX + 3*inc_value))
    .WillOnce(DoAll(SaveArg<0>(cfg.paramX_ptr), Return()));
//expectation 2
EXPECT_CALL(cfg, setParamX(cfg.paramX + 2*inc_value))
    .WillOnce(DoAll(SaveArg<0>(cfg.paramX_ptr), Return()));
//expectation 1
EXPECT_CALL(cfg, setParamX(cfg.paramX + inc_value))
    .WillOnce(DoAll(SaveArg<0>(cfg.paramX_ptr), Return()));

client.incParamXBy(inc_value); //this will match expectation 1
//this will match expectation 2
client.incParamXBy(inc_value); //this will match expectation 3

Is it the only way to maintain state inside a mock object? Of course not. First of all, we could have an equivalent test without maintaining state inside out mock object at all. We could have written all method calls and all expectations using pre-calculated values that we know validate Client's behaviour. The point is that state maintenance gives us more flexibility that may be advantageous in case we want to write a number of similar tests (e.g. test the same behaviour for a range of parameter values or test different behaviours that rely accessing value previously stored in a mock).

Secondly, we can always implement state maintenance by using Invoke. Calling another function or method allows us not only to an equivalent to SaveArg, but also more complex state maintenance cases.

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)

Creating and passing new objects through a method parameter
But what if we want to return a new object through a method parameter? Sometimes caller passes a pointer-to-pointer to a method that is supposed to create a new object and assign its address to the method parameter. Let's modify our example above so that:
  • the caller (class Client) has a private member:
Record * rec;
  • the caller (class Client) has the following method:
void Client::getNewRec()
        // we are passing Record ** (pointer to pointer) to createNewRecord
        // and Generator is supposed to allocate memory
  • our Generator.h has the following declaration:
virtual void createNewRecord(Record ** rec) = 0;
  • which results in the following declaration in MockGenerator.h:
MOCK_METHOD1(createNewRecord, void (Record ** rec));

How can we now emulate the desired behavior in a test code? A straightforward way of doing this would be:

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

    EXPECT_CALL(gen, createNewRecord(_))


Where my_create is a small function that does the trick:

void my_create(Record ** rec)
         *rec = new Record(1,2,3);
But isn't it awkward? The need to define this small function, the hard-coded constructor's parameters... It would  be much more convenient if we had a Google Mock action that could actually create the new object and assign its address to the pointer. Then, in our test, we could simply write:


The CreateAndPass action must be smart enough to create an object of a certain type (Record), create it with the parameters that we specify (1,2,3) and do the proper assignment to the pointer. For a constructor that takes three parameters, as in the example above, our new action would look like this:

                HAS_1_TEMPLATE_PARAMS(typename, T), // the type of object to be created
                AND_3_VALUE_PARAMS(p0, p1, p2))         // constructor parameters
    // we are using TR1; assign the pointer of the newly created object to dereferenced call parameter
    // this is the only parameter of the call in this case, so it has the index of 0

  *(::std::tr1::get<0>(args)) = new T(p0, p1, p2);

That's it. This example can be easily extended for different constructors that take less or more parameters. Since the action is templatized, we can use it to construct objects of any class.

Piotr's Less Obvious Advice on Google Mock: Mutual method calls

Imagine that object A calls method M of object B and B is a mock object. Let's assume further that if B were real, calling the M method would result in B calling a method on A (M would call an A's method from its body). Suppose we want to simulate the same behavior with a mock object. We have a "master" and "slave" objects called Starter and Startee, respectively.

class Starter
  Starter(Startee & startee, int vol);
  virtual ~Starter() {}

  void start();
  void configure();

  Startee & startee_;
  int vol_;


// implementation of the above Starter methods
Starter::Starter(Startee & startee, int vol) : startee_(startee), vol_(vol)

// Starter will call run method on startee
void Starter::start()

// this method is supposed to be called by Startee as a result of calling
void Starter::configure()

And now, Startee:

class Startee

  virtual ~Startee() {}

  virtual void run() = 0;
  virtual void setVolume(int volume) = 0;

And MockStartee:

class MockStartee : public Startee

  MOCK_METHOD0(run, void());
  MOCK_METHOD1(setVolume, void(int volume));

In the test, we will need to tell the mock object to call configure method once the Starter object calls run method on MockStartee:
TEST(StarterTest, MutualCall)
  MockStartee startee;
  Starter starter(startee, 10);
  EXPECT_CALL(startee, setVolume(10))
  EXPECT_CALL(startee, run())
    .WillOnce(WithoutArgs(Invoke(&starter, &Starter::configure)));


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.

Piotr's Less Obvious Advice on Google Mock: Assigning values through method calls

On many occasions, we may want to test a real object by passing to it prepared buffers of data (characters, bytes, etc.) that are filled in when the object calls a mock method. This can be achieved by using SetArrayArg.

Suppose we have a Client object that implements a find method, which takes an array of characters as input argument. The method queries a Driver object for chunks of data (other arrays of characters of the same size as the input argument) and compares each chunk with the input array:

void Client::find(char * buf)
    char tmp_buf[buflen];
    bool found = false;

    while(!found && _drv.getDataChunk(tmp_buf))
        int i = 0;
        while(i < buflen && buf[i] == tmp_buf[i])

        if(i == buflen)
            found = true;

        cout << "Found matching chunk of data." << endl;
        cout << "No matching chunk of data found." << endl;

Client assumes that Diver implements the following contract:
  • if there is no more data chunks, getDataChunk will return false,
  • otherwise, it will return true and will fill in the buffer passed to it through pointer as input, with next chunk of data.
class Driver

    virtual ~Driver() {}

    virtual bool getDataChunk(char *) = 0;

class MockDriver : public Driver

    MOCK_METHOD1(getDataChunk, bool(char *));

Let's now consider a test in which we want to simulate that a matching chunk of data is found on the first call of getDataChunk.

TEST(ClientTest, FindsAMatchOnFirstCall)
    MockDriver drv;
    Client client(drv);

        //this is the buffer that will be searched for
    char buf [] = {'a','a','a','a','a','a','a','a'};

        //this is the matching buffer that will be returned by MockDriver
    char bufA [] = {'a','a','a','a','a','a','a','a'};

    EXPECT_CALL(drv, getDataChunk(_))
        .Times(1) //we are expecting just one call, since the first call will return the matching buffer

                //the mock will return true and before doing so it will copy the contents of bufA into the table
                //pointed to by the pointer passed to getDataChunk method as the input parameter
        .WillOnce(DoAll(SetArrayArgument<0>(bufA, bufA+8), Return(true)));

Exercise: try to modify the code above to validate your expectations on Client::find method when there is no matching chunk of data.

See also