Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gmock TypedEq same string different address

I am trying to set expectation on a gmock object. The expectation should apply whenever "avout" is passed as an argument to my method. I set up the expectation like this:

EXPECT_CALL(actx_mock, getDeviceClientService(TypedEq<const char*>("avout"),_,_)).WillOnce(DoAll(SetArgPointee<2>(&mockAVOut), Return(0)));

TypedEq is needed because the method is overloaded, accepting either a string or a const char *. When I run my test, I get the following error:

CAniSpiceServices_test.cpp:1357: EXPECT_CALL(actx_mock, getDeviceClientService(TypedEq<const char*>("avout"),_,_))...
  Expected arg #0: is equal to 0x4dbf41 pointing to "avout"
           Actual: 0x7fbc6861370d pointing to "avout"

So it looks like even though the string is the same, since it is pointing do a different instance of that string at a different address, it doesn't match? Is there a way to make it match on any string that matches that value, regardless of address?

like image 870
Dustin Wilhelmi Avatar asked Nov 02 '15 16:11

Dustin Wilhelmi


People also ask

What is difference between On_call and Expect_call?

So use ON_CALL by default, and only use EXPECT_CALL when you actually intend to verify that the call is made.

What is matcher in Gtest?

A matcher matches a single argument. You can use it inside ON_CALL() or EXPECT_CALL() , or use it to validate a value directly using two macros: Macro.

How do you mock in gMock?

Using the Turtle interface as example, here are the simple steps you need to follow: Derive a class MockTurtle from Turtle . Take a virtual function of Turtle (while it's possible to mock non-virtual methods using templates, it's much more involved). In the public: section of the child class, write MOCK_METHOD();

What is expect call in gMock?

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) .


1 Answers

OK, I figured it out, so I thought I would post an answer for anyone else struggling with this.

As it turns out, TypedEq<type> is just shorthand for Matcher<type>(Eq()), and Eq compares addresses, not values, of strings. If the test and the class under test are both compiled in the same compilation unit, and you use raw strings both for the expectation and the call, this is fine as the compiler optimizes the two raw strings into the same address. If your test and your class under test are in different compilation units, then the raw strings end up with different addresses, and this fails.

What I did to fix the problem was instead of using TypedEq<type>, I used Matcher<type>(StrEq()), since StrEq compares the string values rather than the addresses.

like image 91
Dustin Wilhelmi Avatar answered Oct 25 '22 13:10

Dustin Wilhelmi