Google Mock

Fake Object
Implements the same interface as the real object.
Does not support expectations
Mock Object
Fake Object which also supports expectations - see below.

Defining Mock Classes

Setting Expectations

//
// MATCHERS
// - the expected parameters
// - use _ if you do not need to verify the parameters
//
// CARDINALITY
// - this is expected to be called N times (specified via cardinality)
//
// ACTIONS
// - the 1st time it is called, the 1st action will fire
// - the 2nd time it is called, the 2nd action will fire
// - the 3rd - nth time it is called, the last action will fire
//
EXPECT_CALL (mock_object, method(matchers))
    .Times (cardinality)
    .WillOnce(action)
    .WillOnce(action)
    .WillRepeatedly(action);

Actions

Return A Value

// return 100
Return (100)

// return "Hello, World!"
Return ("Hello, World!")

Substitute Another Function/Method

//
// invoke function/functor f - arguments will be passed
//
Invoke (f)


//
// invoke object method 
//
Invoke (object_ptr, object_method_ptr)

// e.g.
Invoke (&foo, &Foo::bar)


//
// invoke function/functor without arguments
//
InvokeWithoutArggs (f)


//
// invoke object method which takes no arguments
//
InvokeWithoutArgs (object_ptr, object_method_ptr)

Putting it All Together

#include "gtest/gtest.h"
#include "gmock/gmock.h"

using ::testing::_;

#include <string>
#include <iostream>


class Foo 
{
    virtual void print_two_strings (const std::string& s1, const std::string& s2)
    {
        std::cout << s1 << " " << s2 << std::endl;
    }
};

class MockFoo : public Foo
{
    public:

        MOCK_METHOD2 (print_two_strings, void(const std::string& s1, const std::string& s2));
};

TEST (MockFoo, FooTest)
{
    std::string s1 = "s1";
    std::string s2 = "s2";

    MockFoo mockFoo;

    EXPECT_CALL (mockFoo, print_two_strings(_, _));

    mockFoo.print_two_strings(s1,s2);
}