gmock TypedEq same string different address
Asked Answered
C

1

6

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?

Clomp answered 2/11, 2015 at 16:43 Comment(2)
Please could you post the full EXPECT_CALL fn?Treva
OK, did so. Didn't think it mattered what it did after matching since it isn't matching.Clomp
C
6

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.

Clomp answered 2/11, 2015 at 19:48 Comment(1)
More specifically Eq() compares addresses for C-style strings. For std::string, Eq() works just fine.Machellemachete

© 2022 - 2024 — McMap. All rights reserved.