Home > Back-end >  How to keep the parameter the same in gtest
How to keep the parameter the same in gtest

Time:08-18

Suppose the function

bool foo(int& num) {
     // do something and change the num
     return true;
}

Want the num to be the same before and after calling foo without caring what happens in foo.

CodePudding user response:

You should not pass the parameter "num" as reference "&". Pass it as value: bool foo(int num) {...} num outside foo() will stay the same.

Here is more about passing by reference: https://www.w3schools.com/cpp/cpp_function_reference.asp

CodePudding user response:

Solution 1:

Copy the parameter value:

int prev_num = num;
foo(num);
num = prev_num;

Solution 2: Use a wrapper

// Wrapper uses pass by value for num
bool fooWrapper(int num) {
  return foo(num);
}

// Then later use the fooWrapper instead of foo:
fooWrapper(num);

CodePudding user response:

Your question is to fuzzy to be sure what is proper answer.

Here is my guess:
I assume that you want test that foo do not change value of argument in some cases:

struct Param
{
    int value;
};

class MagicFoo : public testing::TestWithParam<Param>
{};

TEST_P(MagicFoo, ArgIsNotChanged)
{
    auto x = GetParam().value;
    ASSERT_TRUE(foo(x));
    ASSERT_THAT(x, GetParam().value);
}

Full live demo

  • Related