I wanted to test a function which returns some user defined type value. I knew that I can test basic int, float, double etc with EXPECT_EQ
, EXPECT_FLOAT_EQ
etc but not for user defined type. any clue?
Asked
Active
Viewed 2.4k times
14

kmas
- 6,401
- 13
- 40
- 62

Amaresh Kumar
- 586
- 1
- 8
- 20
-
1Seeing how it'll just do something like (val1 == val2) you can just override the == operator for your user defined type value. – Schoentoon Jun 11 '14 at 12:14
2 Answers
6
There must be some way to check something.
a) return type is a data structure, where you can check the values of it's member variables :
struct A {
int v1;
float v2;
char v4;
};
Then use EXPECT_EQ
, EXPECT_FLOAT_EQ
and available macros :
A a1{ 3, 2.2, 'a' };
A a2{ 4, 2.5, 'b' };
EXPECT_EQ( a1.v1, a2.v2 );
or even check like this if POD :
EXPECT_TRUE( 0 == std::memcmp( &a1, &a2, sizeof(a1) ) );
b) the return type has operator==
implemented :
bool operator==( const A& lh, const A& rh ) {
return std::make_tuple( lh.v1, lh.v2, lh.v4 ) == std::make_tuple( rh.v1, rh.v2, rh.v4 );
}
Then compare with EXPECT_EQ
:
A a1{ 3, 2.2, 'a' };
A a2{ 4, 2.5, 'b' };
EXPECT_EQ( a1, a2 );
or with EXPECT_TRUE
:
EXPECT_TRUE( a1 == a2 );
4
Override the == operator. :)
class Object
{
public:
bool operator==(const Object& other) const
{
return (this->member == other.member); // Modify this depending on the equality criteria
}
private:
int member;
}
On the test part:
Object a, b;
EXPECT_EQ(a, b); // Should work

twenty04
- 116
- 5