Search code examples
c++unit-testingc++17googletestgooglemock

is it ok for arguments and expects go out of scope


I'm wondering is it ok if arguments and expects are going out of scope when they actually be matched later? like this:

struct Object
{
    // ...
};

struct TestFixture : public testing::Test
{
    MOCK_METHOD1(handle, void(Object obj));
};

TEST_F(TestFixture, Basic)
{
    {
        Object obj; // = get different obj
        EXPECT_CALL(*this, handle(obj));
    }

    {
        Object obj; // = get different obj
        EXPECT_CALL(*this, handle(obj));
    }

    {
        Object obj; // = get different obj
        EXPECT_CALL(*this, handle(obj));
    }

    // call handle 3 times
}

all the 3 obj variable will go out of scope, also will EXPECT_CALL create some kind of local variables there? Is this test ok in gtest? Thanks.


Solution

  • From reference/matchers.html

    Except Ref(), these matchers make a copy of value in case it’s modified or destructed later.

    So you are fine.