GoogleMock是否让我在模拟类中实现析构函数?

时间:2016-04-15 20:55:22

标签: c++ googletest googlemock

运行make时我一直收到这些错误:

debug/main.o: In function `MockMQAdapter<SomeClass>::MockMQAdapter()':
/source/Tests/testsfoo/MockMQAdapter.h:30: undefined reference to `MQAdapter<SomeClass>::~MQAdapter()'
debug/main.o:(.rodata._ZTVN2TW9MQAdapterI6ThingyEE[_ZTVN2TW9MQAdapterI6ThingyEE]+0x10): undefined reference to MQAdapter<SomeClass>::~MQAdapter()'
debug/main.o:(.rodata._ZTVN2TW9MQAdapterI6ThingyEE[_ZTVN2TW9MQAdapterI6ThingyEE]+0x18): undefined reference to `MQAdapter<SomeClass>::~MQAdapter()'
debug/main.o:(.rodata._ZTVN2TW9MQAdapterI6ThingyEE[_ZTVN2TW9MQAdapterI6ThingyEE]+0x20): undefined reference to `MQAdapter<SomeClass>::publish(std::string const&, std::string &message)'

这是我的代码:

#include <gmock/gmock.h>

template<typename S>
class MQAdapter {
public:
    MQAdapter(const std::string host, uint16_t port);
    virtual ~MQAdapter();
    virtual void publish(const std::string queue, std::string message);
};

MQAdapter::MQAdapter(const std::string host, uint16_t port) {}

//Generated by gmock_gen.py
template <typename T0>
class MockMQAdapter : public MQAdapter<T0> {
 public:
  MOCK_METHOD2_T(publish,
      void(std::string, std::string));
};

我非常密切地关注了谷歌模拟指南。我不明白这些错误是什么意思。这是我的测试结果:

TEST(MyTest, ExpectCall) {
  MockMQAdapter<SomeClass> *adapter = new MockMQAdapter<SomeClass>("host", 1);
  EXPECT_CALL(*adapter, publish("hi", "hello"));
  adapter->publish("hi", "hello");
}

1 个答案:

答案 0 :(得分:1)

您已声明MQAdapter析构函数,但未定义它。因此链接器在尝试解决它时会抱怨。提供一个定义,default就足够了,即virtual ~MQAdapter() = default;

另一方面,构造函数的定义应该使用模板参数内联或限定:

template <typename S>
MQAdapter<S>::MQAdapter(const std::string host, uint16_t port) {}

我想这是因为这只是一个例子,但你没有使用MQAdapter模板参数来做任何事情,所以它可能是一个普通的类。