pointers as parameters to EXPECT_EQ

3,029 views
Skip to first unread message

Chreston Miller

unread,
Jul 11, 2011, 12:33:34 PM7/11/11
to Google C++ Testing Framework
I want to use gtest for verifying some results in which dynamic memory
is used. I create new instances of my objects, perform some processing
and want to verify what they contain. I have pointers to the objects.
However, when I use EXPECT_EQ, it only compares the pointer addresses,
not the object it points to.

Example:

#include <foo.h> //includes class foo

foo* actualFoo = new foo();
foo* expectedFoo = new foo();

...fill expectedFoo with values you want...
...perform operations that give values to actualFoo...

EXPECT_EQ(expectedFoo, actualFoo); //this compares the addresses and
not the actual foo objects, I also have the appropriate assignment
operator overloaded for class foo

The major issue I am running into is that I have a complicated nesting
of STL containers in which the stored data are pointers to objects. I
am very happy that I can pass STL objects to EXPECT_EQ but my
containers store pointers, in which case I get the above behavior. Is
there something I am missing? Thanks!

Chreston


Keith Ray

unread,
Jul 11, 2011, 12:52:37 PM7/11/11
to Chreston Miller, Google C++ Testing Framework
Use Predicate Assertions, defining your own MyTypeEqual function as per...

http://code.google.com/p/googletest/wiki/AdvancedGuide#Predicate_Assertions_for_Better_Error_Messages

bool MyTypeEqual(MyType* a, MyType* b) { return *a == *b; }

MyType* x = new MyType...
MyType* y = new MyType...

EXPECT_PRED2(MyTypeEqual, x, y);

You might also get the behavior you want by defining something like:

bool operator==(YourType* ptr1, YourType* ptr2) { return *ptr1 == *ptr2; }

Note this is different than the bool operator== for YourType -- you're
defining the equality function to pointers to your type.

Does this help?

--
C. Keith Ray

Coach, Trainer, and Developer at Industrial logic, Inc.
http://industriallogic.com/shop  "Amplify Your Agility"
Coaching and Live and Web-based Training

Reply all
Reply to author
Forward
0 new messages