Gmock Compliance Structures

How can I match the value of an element in a union for an input argument, for example, if I make fun of a method with the following signature -

struct SomeStruct { int data1; int data2; }; void SomeMethod(SomeStruct data); 

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

+9
source share
4 answers

Google provides good documentation on using gmock, complete with sample code. I highly recommend checking this out:

https://github.com/google/googletest/blob/master/googlemock/docs/cook_book.md#using-matchers

As you pointed out, the default equality operator ( == ) is not automatically created for class types (including POD). Since this operator is used by gmock when matching parameters, you need to explicitly define it in order to use the type just like any other type (as shown below):

  // Assumes 'SomeMethod' is mocked in 'MockedObject' MockedObject foo; SomeStruct expectedValue { 1, 2 }; EXPECT_CALL(foo, SomeMethod(expectedValue)); 

So, the easiest way to handle this is to define an equality operator for the structure:

 struct SomeStruct { int data1; int data2; bool operator==(const SomeStruct& rhs) const { return data1 == rhs.data1 && data2 == rhs.data2; } }; 

If you do not want to go this route, you can use Field Match to map the parameter based on the values โ€‹โ€‹of its member variables. (However, if the test is interested in comparing equality between instances of the structure, this is a good sign that other code will be interesting. Therefore, you probably just need to define operator== and end it.)

+6
source

If you need to explicitly check the specific value of only one field of the structure (or one "property" of the class), gmock has an easy way to check this using the definitions of "Field" and "Property". With structure:

 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 ))); 
+6
source

This was mainly answered above, but I want to give another good example:

 // some test type struct Foo { bool b; int i; }; // define a matcher if ==operator is not needed in production MATCHER_P(EqFoo, other, "Equality matcher for type Foo") { return std::tie(arg.b, arg.i) == std::tie(other.b, other.i); } // example usage in your test const Foo test_value {true, 42}; EXPECT_CALL(your_mock, YourMethod(EqFoo(test_value))); 
0
source

Source: https://habr.com/ru/post/970042/


All Articles