Search code examples
c++googletestgooglemock

google mock - how to EXPECT_CALL on a variable name i.e. identifier


I have a function whose call I need to detect i.e.

EXPECT_CALL(MockClass_obj, target_func());

The signature is:

void MockClass::target_func(HANDLE_t handle);

Argument handle is an opaque type and it's a global set in some other function so yes, I will need to stub it.

Here's the problem: inside the function I am testing, I call MockClass::target_func with a few different arguments depending on the branches taken:

//MockClass inherits Class, call f1() with instance of MockClass
void f1(int a, Class & obj)
{
    switch(a):
    {
    case 0:
        obj.target_func(global_handle_1);
        break;
    case 1:
        obj.target_func(global_handle_2);
        break;
    default:
        obj.target_func(global_handle_3);

    }
}

QUESTION

How do I do an expect call based on the NAME of the argument? I need to detect which path was taken.

Since all the global_handle_[x] variables will be stubbed out i.e. set to arbitrary value, I could set them to global_handle_<x>=<x> and then EXPECT_CALL(MockClass_obj, target_func(<x>));

I guess that's good enough but to be more robust, ideally I'd like to EXPECT_CALL on a variable name?

Is this possible?


Solution

  • What you are asking for is basically not possible with C++. target_func is passed its argument by value, so there is no way for it (or the mocked version of it), to know how the value was calculated. The call could be obj.target_func(global_handle_1); or it could be obj.target_func(global_handle_2 - 1); (if those expressions happen to have identical value).

    I think your best option is to give each global variable a unique value, and then EXPECT the correct value. I would a) space the unique values well apart; b) rely on code reviews to spot people doing arithmetic on handle values.

    If target_fun took it's argument by reference, then you might be able to do an EXPECT based on the address of the reference - but I wouldn't bother.