给出以下模拟方法
MOCK_METHOD2(send, int(const void* pBuffer, size_t szBuffer));
以及以下用法
EXPECT_CALL(socketMock, send(_, _))
.Times(1)
.WillOnce(ReturnArg<1>());
由于 szBuffer 隐式转换为 int 返回类型,因此会在 ReturnArg 中生成警告。
这是代码示例:
#include <cstddef>
#include <cstdint>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
class ISocket {
public:
virtual int Send(const uint8_t* payload, const std::size_t payloadLength, std::size_t& sentLength) = 0;
};
class SocketMock : public ISocket {
public:
MOCK_METHOD3(Send, int(const uint8_t*, const std::size_t, std::size_t&));
};
class MySender
{
public:
static void Ping(ISocket& socket)
{
std::size_t bytesSent;
uint8_t payload[64];
memset(payload, 0, sizeof(payload));
socket.Send(payload, sizeof(payload), bytesSent);
if (bytesSent != sizeof(payload))
throw std::runtime_error("Socket transmission failed");
}
};
TEST(SocketSend, ReturnsBytesTransmitted)
{
SocketMock socket;
EXPECT_CALL(socket,
Send(
::testing::_, // payload
::testing::_, // payload length
::testing::_ // return by param, bytes sent
)).Times(1)
.WillOnce(::testing::ReturnArg<1>());
MySender::Ping(socket);
::testing::Mock::VerifyAndClearExpectations(&socket);
}
GTEST_API_ int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
这是编译器警告:
googletest\googlemock\include\gmock/gmock-more-actions.h(165): 警告 C4267: 'return': 从 'size_t' 到 'int' 的转换,可能丢失数据(编译源文件 TestMain.cpp)
无论如何,有没有办法让 GMock 使用 static_cast 来更改返回类型以消除类型转换警告?