Gmock - matching structures

If there a need to explicitly test for specific value of just one field of a struct (or one "property" of a class), gmock has a simple way to test this with the "Field" and "Property" definitions. With a struct:

EXPECT_CALL( someMock, SomeMethod( Field( &SomeStruct::data1, expectedValue )));

Or, alternatively if we have SomeClass (intead of SomeStruct), that has private member variables and public getter functions:

EXPECT_CALL( someMock, SomeMethod( Property( &SomeClass::getData1, expectedValue )));

After reading through the Google mock documentation in detail, I solved my problem as documented in Defining Matchers section. (An example would have been great!)

So the solution is to use the MATCHER_P macros to define a custom matcher. So for the matching SomeStruct.data1 I defined a matcher:

MATCHER_P(data1AreEqual, ,"") { return (arg.data1 == SomeStructToCompare.data1); }

to match it in an expectation I used this custom macro like this:

EXPECT_CALL(someMock, SomeMethod(data1AreEqual(expectedSomeStruct)));

Here, expectedSomeStruct is the value of the structure.data1 we are expecting.

Note that, as suggested in other answers (in this post and others), it requires the unit under test to change to make it testable. That should not be necessary! E.g. overloading.

Tags:

C++

Gmock