What is wrong with my attempts to mock a simple C++ method with googlemock?

流过昼夜 提交于 2019-12-02 10:29:33

Looks like you're invoking the copy constructor for MockSocket somewhere in TestBody without a cast.

I finally got it sorted. What was tripping me up is that I wanted to use a pointer, but googlemock works with classes. Here's what works:

#include "gmock/gmock.h"
#include "gtest/gtest.h"
// C standard library includes omitted
#include "MockSocket.h"
#include "Network.h"

using ::testing::Return;
namespace JrStream {
  class NetworkTest : public ::testing::Test {
  protected:
    Network net;
    MockSocket sock;
  };

  TEST_F(NetworkTest, InitCallsSocket) {
    EXPECT_CALL(sock, Socket(AF_INET, SOCK_STREAM, 0))
        .Times(1)
        .WillOnce(Return(5)); //fake file descriptor

    ASSERT_TRUE(net.init(&sock));
  }
} // namespace
// gtest boilerplate main() omitted

This is well and good, but I wonder how to make this work if I really needed my pointers. Sounds like an exercise for the reader. ;)

How about:

TEST_F(NetworkTest, InitCallsSocket) {
EXPECT_CALL(*((MockSocket)*socket_ptr), Socket(AF_INET, SOCK_STREAM, 0))
    .Times(1)
    .WillOnce(Return(5)); //fake file descriptor

ASSERT_TRUE(net.init(socket_ptr));

}

(Disclaimer - I did not check if it compiles...)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!