Test a std::vector argument from a MOCK_METHOD call with gtest

192 Views Asked by At

Is there a way to store the data from an vector reference to a MOCK_METHOD?

I have following mocked interface:

MOCK_METHOD(bool, SetData, (const std::vector<uint8_t>& data), (override));

And I would like to test the data that is sent to this mock method, ex.

std::vector<uint8_t> test_data;
EXPECT_CALL(testClass, SetData(_)).SaveArg<0>(&test_data);
EXPECT_EQ(test_data[0], 42);
2

There are 2 best solutions below

1
alagner On BEST ANSWER

It can be done, see below. Note though, that matchers, even the more complex ones, are oftentimes considered the cleaner solution anyway.

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <vector>

using namespace testing;

struct I
{
    virtual bool setData(const std::vector<std::uint8_t>&) = 0;
    virtual ~I() = default;
};

struct S : I
{
    MOCK_METHOD(bool, setData, (const std::vector<uint8_t>& data), (override));
};


TEST(aaa, bbb)
{
    S s;
    std::vector<std::uint8_t> target;
    std::vector<std::uint8_t> source{1,2,3,4,5};
    EXPECT_CALL(s, setData).WillOnce(
        DoAll(
            SaveArg<0>(&target),
            Return(true)
        )
    );
    s.setData(source);
    EXPECT_EQ(source, target);
}

https://godbolt.org/z/4MrEPvaa3

1
Yksisarvinen On

You don't have to save the argument at all. Just use matcher to check if the content matches your expectation:

TEST(X, Y)
{
    std::vector<uint8_t> expectedData {42, 1, 2, 3};
    // if not matcher is specified explicitly, `::testing::Eq` is used
    EXPECT_CALL(testClass, SetData(expectedData)).WillOnce(::testing::Return(true));
}