简体   繁体   中英

C++ gmock - How we can read/get the parameter value of a function of cpp file in unit test cpp file

I have a project_file.cpp file like:

//Private Function definition
void my_fun(int &value)
{
    //Do something
}

//Function Calling
int value = any_other_function();
myclass.my_fun(val);

Now I need to fetch val parameter value through mock my_fun() method as below:

utc_file.cpp

namespace TEST
{
    int my_fun_val;  //global variable
    class myTest : public Test
    {
        //Do something
    };

    ACTION(getMyFunctionVal)
    {
        my_fun_val = arg0; //copy val value
    }

    TEST_F(myTest, readValueOfFunction)
    {
        EXPECT_CALL(m_MyFunMock, my_fun(_)).WillOnce(::testing::DoAll(getMyFunctionVal(), 
        Return(true)));
        EXPECT_EQ(my_fun_val, 5);
    }
}

Above code work fine with global varibale "my_fun_val" but I don't want to use global variable. And we cannot make function (my_fun()) as "public". Please guide other way to get the parameter at unit test file.

Another way to solve above problem, we can compare the value inside the ACTION method.

utc_file.cpp

namespace TEST
{
    class myTest : public Test
    {
        //Do something
    };

    ACTION_P(getMyFunctionVal, value)
    {
        EXPECT_EQ(arg0, value); //Here we can compare the value but unable to fill it as in reference variable and pass to callie method.
    }

    TEST_F(myTest, readValueOfFunction)
    {
        int expectedValue = 5;
        EXPECT_CALL(m_MyFunMock, my_fun(_)).WillOnce(::testing::DoAll(getMyFunctionVal(expectedValue), 
        Return(true)));
    }
}

Note: Here we cannot able to use SaveArg() OR SaveArgPointee() due to the Pointer reference usage. Currently gmock doesn't provide any method/mechanism to read parameter value when passed as a reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM