NiladriBose NiladriBose - 1 year ago 284
C++ Question

Gmock - matching structures

How can I match value of an element in a union for an input argument e.g - if I mock a method with the following signatiure -

struct SomeStruct
int data1;
int data2;

void SomeMethod(SomeStruct data);

How can I match that mock for this method was called with correct value in argument?

Answer Source

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.dat1 == 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download