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
- The destructor and any method you wish to override must be declared
virtual
- Derive a mock class from the class you which to provide a mock implementation of
- In the
public:
section of the of the child class, use MOCK_METHODn()
or MOCK_CONST_METHODn()
for each method in which you're overriding. n is the number of arguments the method accepts
- Pass the method name (without any quotes, etc.) as the first parameter to the macro
- Pass the remainder of the function signature as the second parameter to the macro
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);
- Expectations will be checked when the mock object is destructed.
- Expectations must be specified before the mock functions are called
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);
}