gmock SetArgReferee:设置不可复制的不可移动对象

时间:2020-07-27 19:09:49

标签: c++ boost googletest googlemock boost-beast

我正在使用gmock并嘲笑了一个需要 boost::beast::http::response_parser作为out参数。功能 签名看起来像:

error_code readFromSocket(boost::beast::http::response_parser& resp);

现在,要测试此功能,我嘲笑并像下面这样使用EXPECT_CALL

boost::beast::http::response_parser respObject;
// set status code in respObject
EXPECT_CALL(mockObject, readFromSocket(_))
    .Times(1)
    .DoAll(SetArgReferee<0>(respObject), Return(err::success));

它返回一个operator= deleted compilation错误。我试过了 使用ByRefByMove,使用std::ref的各种组合,但没有一个 有效,我知道为什么它们不起作用。

以前有没有人遇到过类似情况并且知道如何解决此问题 错误?请让我知道是否需要澄清。

谢谢。

编辑

readFromSocket如下所示:

template<typename T>
error_code readFromSocket(beast::http::response_parser<T>& resp,
                          boost::asio::yield_context yield)
{
    // read from socket using beast::http::async_read
    return success;
}

这就是我的称呼。

beast::http::response_parser<beast::http::string_body> resp;
resp.body_limit((std::numeric_limits<std::string::size_type>::max)());
auto ec = readFromSocket(resp, yield);

// after this I do error handling and response status code handling.

1 个答案:

答案 0 :(得分:0)

我试图实现相同的行为,而 WithArg 是关键。这是我最终得到的一个例子:

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


using namespace testing;

struct NonCopyable {
    NonCopyable() = default;
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable& operator=(const NonCopyable&) = delete;

    int a;
};

struct WorkWithNonCopyable {
    virtual ~WorkWithNonCopyable() = default;

    virtual bool modify_non_copyable(NonCopyable& nc) = 0;
};

struct WorkWithNonCopyableMock {
    MOCK_METHOD1(modify_non_copyable, bool(NonCopyable& nc));
};

TEST(WorkWithNonCopyableTest, NormalizedRoiDetectorTest) {
    WorkWithNonCopyableMock work_with_non_copyable_mock{};

    EXPECT_CALL(work_with_non_copyable_mock, modify_non_copyable(_))
        .WillOnce(DoAll(WithArg<0>([](auto& arg) { arg.a = 42; }), Return(true)));

    NonCopyable non_copyable;
    ASSERT_TRUE(work_with_non_copyable_mock.modify_non_copyable(non_copyable));
    ASSERT_EQ(non_copyable.a, 42);
}