c++ - 为了模拟对象,我们是否应该将所有成员函数声明为虚拟(C++)?

标签 c++ performance googletest virtual-functions googlemock

虚函数在运行时有开销。但是如果没有虚函数,我们就不能模拟对象来做单元测试。

这方面的最佳实践是什么?

谢谢!

最佳答案

But without virtual function, we can not mock objects to do unit test.

这不完全正确。来自 Google Mock Cookbook你实际上可以模拟非虚函数:

One way to do it is to templatize your code that needs to use a packet stream. More specifically, you will give your code a template type argument for the type of the packet stream. In production, you will instantiate your template with ConcretePacketStream as the type argument. In tests, you will instantiate the same template with MockPacketStream. For example, you may write:

template <class PacketStream>
void CreateConnection(PacketStream* stream) { ... }

template <class PacketStream>
class PacketReader {
 public:
  void ReadPackets(PacketStream* stream, size_t packet_num);
 };

Then you can use CreateConnection<ConcretePacketStream>() and PacketReader<ConcretePacketStream> in production code, and use CreateConnection<MockPacketStream>() and PacketReader<MockPacketStream> in tests.

 MockPacketStream mock_stream;
 EXPECT_CALL(mock_stream, ...)...;
 ... set more expectations on mock_stream ...
  PacketReader<MockPacketStream> reader(&mock_stream);
 ... exercise reader ...

关于c++ - 为了模拟对象,我们是否应该将所有成员函数声明为虚拟(C++)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36068981/

相关文章:

c++ - opencv calcHist 在使用 cvtColor 后返回黑色直方图

c# - 提高 linq 查询的性能

javascript 闭包和函数放置

c++ - gtest/gmock 是否有办法对类的每个实例进行 stub ?

c++ - 为 gcov 编译 googletest

c++ - 是否可以使用 testing::NiceMock<> 等价物来包装/配置模拟引用?

c++ - 为什么 sizeof(Base) 与 sizeof(Derived) 没有区别

c++ - C++中的Web访问身份验证?

c++ - 使用通用 vector 大小类型的最佳方法是什么?

c# - Entity Framework 包括性能