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?
Gmock is a mocking framework for the Groovy language. Gmock is all about simple syntax and readability of your tests so you spend less time learning the framework and more writing code. To use Gmock just drop the gmock jar file in your classpath. The current version is gmock-0.8.
In gMock we use the EXPECT_CALL() macro to set an expectation on a mock method. The general syntax is: EXPECT_CALL(mock_object, method(matchers)) . Times(cardinality) .
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.
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 )));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With