2

I am already using gtest for some time but recently wanted to try out gmock. I am trying to mock class with method that returns value but also returns something in output parameter through reference. Here is my small code.

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

using namespace ::testing;

class AReal
{
public:
    virtual bool foo(std::vector<int>& v) const = 0;
};

class AMock : public AReal
{
public:
    MOCK_CONST_METHOD1(foo, bool(std::vector<int>&));
};

class B
{
public:
    B(AReal* _a) : a(_a) {}

    bool foo(std::vector<int>& v) const { return a->foo(v); }

private:
    AReal* a;
};

class FooTest : public Test {};

TEST_F(FooTest,
DummyTestVector) {
    AMock a;
    B b(&a);

    std::vector<int> exp = { 1, 2, 3 };
    EXPECT_CALL(a, foo(_))
        .Times(1)
        .WillOnce(AllOf(SetArgReferee<0>(exp), Return(true)));

    std::vector<int> load;
    EXPECT_TRUE(a.foo(load));
    EXPECT_EQ(exp, load);
}

int main(int argc, char** argv) {
    ::testing::InitGoogleMock(&argc, argv);
    return RUN_ALL_TESTS();
}

However, this code gives me this error.

$ g++ -Wall -Wextra -std=c++14 -I. -o test test.cpp gmock-gtest-all.cc -lpthread
test.cpp: In member function ‘virtual void FooTest_DummyTestVector_Test::TestBody()’:
test.cpp:40:61: error: no matching function for call to ‘testing::internal::TypedExpectation<bool(std::vector<int>&)>::WillOnce(testing::internal::AllOfResult2<testing::SetArgRefereeActionP<0, std::vector<int> >, testing::internal::ReturnAction<bool> >::type)’
         .WillOnce(AllOf(SetArgReferee<0>(exp), Return(true)));
                                                             ^
In file included from test.cpp:2:0:
gmock/gmock.h:10172:21: note: candidate: testing::internal::TypedExpectation<F>& testing::internal::TypedExpectation<F>::WillOnce(const testing::Action<F>&) [with F = bool(std::vector<int>&)]
   TypedExpectation& WillOnce(const Action<F>& action) {
                     ^
gmock/gmock.h:10172:21: note:   no known conversion for argument 1 from ‘testing::internal::AllOfResult2<testing::SetArgRefereeActionP<0, std::vector<int> >, testing::internal::ReturnAction<bool> >::type {aka testing::internal::BothOfMatcher<testing::SetArgRefereeActionP<0, std::vector<int> >, testing::internal::ReturnAction<bool> >}’ to ‘const testing::Action<bool(std::vector<int>&)>&’

If I don't use AllOf but rather specify just one action, either SetArgReferee or Return, everything works just fine. The use of AllOf causes this kind of error. I have found about AllOf here gmock multiple in-out parameters SetArgReferee and basically my code is same as the answer.

Community
  • 1
  • 1
Marek Milkovič
  • 464
  • 1
  • 8
  • 20

1 Answers1

8

After one whole afternoon of trying everything I found out it was just my stupidity. All the time I somehow thought that AllOf == DoAll. Realized it just now.

Marek Milkovič
  • 464
  • 1
  • 8
  • 20