Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use EXPECT_EQ for user defined type

Tags:

c++

googletest

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?

like image 903
Amaresh Kumar Avatar asked Jun 11 '14 12:06

Amaresh Kumar


2 Answers

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 );
like image 77
BЈовић Avatar answered Oct 13 '22 21:10

BЈовић


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
like image 4
twenty04 Avatar answered Oct 13 '22 21:10

twenty04