Googlemock - WillOnce中的多项操作会导致构建错误

时间:2016-02-27 16:24:51

标签: googletest googlemock

我已经使用gtest一段时间,但最近想尝试gmock。我试图使用返回值的方法来模拟类,但也通过引用返回输出参数中的内容。这是我的小代码。

#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();
}

但是,这段代码给了我这个错误。

$ 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>&)>&’

如果我不使用AllOf,而是只指定一个操作,SetArgRefereeReturn,一切正常。使用AllOf会导致此类错误。我在这里发现AllOf gmock multiple in-out parameters SetArgReferee,基本上我的代码与答案相同。

1 个答案:

答案 0 :(得分:4)

经过一整个下午尝试的一切,我发现这只是我的愚蠢。我总是以某种方式认为AllOf == DoAll。刚刚意识到这一点。