|
CheatSheet
Google C++ Mocking Framework Cheat Sheet
Defining a Mock ClassMocking a Normal ClassGiven class Foo {
...
virtual ~Foo();
virtual int GetSize() const = 0;
virtual string Describe(const char* name) = 0;
virtual string Describe(int type) = 0;
virtual bool Process(Bar elem, int count) = 0;
};(note that ~Foo() must be virtual) we can define its mock as #include <gmock/gmock.h>
class MockFoo : public Foo {
MOCK_CONST_METHOD0(GetSize, int());
MOCK_METHOD1(Describe, string(const char* name));
MOCK_METHOD1(Describe, string(int type));
MOCK_METHOD2(Process, bool(Bar elem, int count));
};To create a "nice" mock object which ignores all uninteresting calls, or a "strict" mock object, which treats them as failures: NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. Mocking a Class TemplateTo mock template <typename Elem>
class StackInterface {
...
virtual ~StackInterface();
virtual int GetSize() const = 0;
virtual void Push(const Elem& x) = 0;
};(note that ~StackInterface() must be virtual) just append _T to the MOCK_* macros: template <typename Elem>
class MockStack : public StackInterface<Elem> {
...
MOCK_CONST_METHOD0_T(GetSize, int());
MOCK_METHOD1_T(Push, void(const Elem& x));
};Specifying Calling Conventions for Mock FunctionsIf your mock function doesn't use the default calling convention, you can specify it by appending _WITH_CALLTYPE to any of the macros described in the previous two sections and supplying the calling convention as the first argument to the macro. For example, MOCK_METHOD_1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int n)); MOCK_CONST_METHOD2_WITH_CALLTYPE(STDMETHODCALLTYPE, Bar, int(double x, double y)); where STDMETHODCALLTYPE is defined by <objbase.h> on Windows. Using Mocks in TestsThe typical flow is:
Here is an example: using ::testing::Return; // #1
TEST(BarTest, DoesThis) {
MockFoo foo; // #2
ON_CALL(foo, GetSize()) // #3
.WillByDefault(Return(1));
// ... other default actions ...
EXPECT_CALL(foo, Describe(5)) // #4
.Times(3)
.WillRepeatedly(Return("Category 5"));
// ... other expectations ...
EXPECT_EQ("good", MyProductionFunction(&foo)); // #5
} // #6Setting Default ActionsGoogle Mock has a built-in default action for any function that returns void, bool, a numeric value, or a pointer. To customize the default action for functions with return type T globally: using ::testing::DefaultValue; DefaultValue<T>::Set(value); // Sets the default value to be returned. // ... use the mocks ... DefaultValue<T>::Clear(); // Resets the default value. To customize the default action for a particular method, use ON_CALL(): ON_CALL(mock_object, method(matchers))
.With(multi_argument_matcher) ?
.WillByDefault(action);Setting ExpectationsEXPECT_CALL() sets expectations on a mock method (How will it be called? What will it do?): EXPECT_CALL(mock_object, method(matchers))
.With(multi_argument_matcher) ?
.Times(cardinality) ?
.InSequence(sequences) *
.After(expectations) *
.WillOnce(action) *
.WillRepeatedly(action) ?
.RetiresOnSaturation(); ?If Times() is omitted, the cardinality is assumed to be:
A method with no EXPECT_CALL() is free to be invoked any number of times, and the default action will be taken each time. MatchersA matcher matches a single argument. You can use it inside ON_CALL() or EXPECT_CALL(), or use it to validate a value directly:
Built-in matchers (where argument is the function argument) are divided into several categories: Wildcard
Generic Comparison
Except Ref(), these matchers make a copy of value in case it's modified or destructed later. If the compiler complains that value doesn't have a public copy constructor, try wrap it in ByRef(), e.g. Eq(ByRef(non_copyable_value)). If you do that, make sure non_copyable_value is not changed afterwards, or the meaning of your matcher will be changed. Floating-Point Matchers
These matchers use ULP-based comparison (the same as used in Google Test). They automatically pick a reasonable error bound based on the absolute value of the expected value. DoubleEq() and FloatEq() conform to the IEEE standard, which requires comparing two NaNs for equality to return false. The NanSensitive* version instead treats two NaNs as equal, which is often what a user wants. String MatchersThe argument can be either a C string or a C++ string object:
StrCaseEq(), StrCaseNe(), StrEq(), and StrNe() work for wide strings as well. Container MatchersMost STL-style containers support ==, so you can use Eq(expected_container) or simply expected_container to match a container exactly. If you want to write the elements in-line, match them more flexibly, or get more informative messages, you can use:
These matchers can also match:
where the array may be multi-dimensional (i.e. its elements can be arrays). Member Matchers
Matching the Result of a Function or Functor
Pointer Matchers
Multiargument MatchersThese are matchers on tuple types. They can be used in .With(). The following can be used on functions with two arguments x and y:
You can use the following selectors to pick a subset of the arguments (or reorder them) to participate in the matching:
Composite MatchersYou can make a matcher from one or more other matchers:
Adapters for Matchers
Matchers as Predicates
Defining Matchers
Notes:
Matchers as Test Assertions
ActionsActions specify what a mock function should do when invoked. Returning a Value
Side Effects
Using a Function or a Functor as an Action
The return value of the invoked function is used as the return value of the action. When defining a function or functor to be used with Invoke*(), you can declare any unused parameters as Unused: double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
...
EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));In InvokeArgument<N>(...), if an argument needs to be passed by reference, wrap it inside ByRef(). For example, InvokeArgument<2>(5, string("Hi"), ByRef(foo))calls the mock function's #2 argument, passing to it 5 and string("Hi") by value, and foo by reference. Default Action
Note: due to technical reasons, DoDefault() cannot be used inside a composite action - trying to do so will result in a run-time error. Composite Actions
Defining Actions
The ACTION* macros cannot be used inside a function or class. CardinalitiesThese are used in Times() to specify how many times a mock function will be called:
Expectation OrderBy default, the expectations can be matched in any order. If some or all expectations must be matched in a given order, there are two ways to specify it. They can be used either independently or together. The After Clauseusing ::testing::Expectation;
...
Expectation init_x = EXPECT_CALL(foo, InitX());
Expectation init_y = EXPECT_CALL(foo, InitY());
EXPECT_CALL(foo, Bar())
.After(init_x, init_y);says that Bar() can be called only after both InitX() and InitY() have been called. If you don't know how many pre-requisites an expectation has when you write it, you can use an ExpectationSet to collect them: using ::testing::ExpectationSet;
...
ExpectationSet all_inits;
for (int i = 0; i < element_count; i++) {
all_inits += EXPECT_CALL(foo, InitElement(i));
}
EXPECT_CALL(foo, Bar())
.After(all_inits);says that Bar() can be called only after all elements have been initialized (but we don't care about which elements get initialized before the others). Modifying an ExpectationSet after using it in an .After() doesn't affect the meaning of the .After(). SequencesWhen you have a long chain of sequential expectations, it's easier to specify the order using sequences, which don't require you to given each expectation in the chain a different name. All expected calls in the same sequence must occur in the order they are specified. using ::testing::Sequence;
Sequence s1, s2;
...
EXPECT_CALL(foo, Reset())
.InSequence(s1, s2)
.WillOnce(Return(true));
EXPECT_CALL(foo, GetSize())
.InSequence(s1)
.WillOnce(Return(1));
EXPECT_CALL(foo, Describe(A<const char*>()))
.InSequence(s2)
.WillOnce(Return("dummy"));says that Reset() must be called before both GetSize() and Describe(), and the latter two can occur in any order. To put many expectations in a sequence conveniently: using ::testing::InSequence;
{
InSequence dummy;
EXPECT_CALL(...)...;
EXPECT_CALL(...)...;
...
EXPECT_CALL(...)...;
}says that all expected calls in the scope of dummy must occur in strict order. The name dummy is irrelevant.) Verifying and Resetting a MockGoogle Mock will verify the expectations on a mock object when it is destructed, or you can do it earlier: using ::testing::Mock; ... // Verifies and removes the expectations on mock_obj; // returns true iff successful. Mock::VerifyAndClearExpectations(&mock_obj); ... // Verifies and removes the expectations on mock_obj; // also removes the default actions set by ON_CALL(); // returns true iff successful. Mock::VerifyAndClear(&mock_obj); You can also tell Google Mock that a mock object can be leaked and doesn't need to be verified: Mock::AllowLeak(&mock_obj); Mock ClassesGoogle Mock defines a convenient mock class template class MockFunction<R(A1, ..., An)> {
public:
MOCK_METHODn(Call, R(A1, ..., An));
};See this recipe for one application of it. Flags
|