Search code examples
c++googletest

C++ / GoogleTest - How to test member variable of a class being tested


I'm creating tests for a legacy code and wondering if it is possible to check the values of member variables of a class like this (I know my code below is very lousy, bad example :/. Hope to just please focus on the question):

class Animal
{
public:
   RESULT getInfo();
   int age_;
};

int main()
{
   Animal animal;
   RESULT result = animal.getInfo();

   return 0;
}

RESULT Animal::getInfo()
{
    age_ = rand() % 10 + 1;
    if (age == 5)
    {
        return success;
    }
    else
    {
        return fail;
    }       
}

And in my test (using Google Test), I call getInfo():

EXPECT_EQ(success, sut_->getInfo());

However, this just verifies that the result of getInfo() is success. Is there any other way for me to check the value of age_ without adding a new method/changing the return value? Thanks!


Solution

  • As you have already made age_ public, you can just add another EXPECT_EQ statement. If making age_ public was not intentional then you will have to come with a method to access age_ in GTest code.