Virtual functions have costs during runtime. But without virtual function, we can not mock objects to do unit test.
What is the best practice of this?
Thanks!
But without virtual function, we can not mock objects to do unit test.
That's not completely true. As from the Google Mock Cookbook you actually can mock non-virtual functions:
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>()
andPacketReader<ConcretePacketStream>
in production code, and useCreateConnection<MockPacketStream>()
andPacketReader<MockPacketStream>
in tests.MockPacketStream mock_stream; EXPECT_CALL(mock_stream, ...)...; ... set more expectations on mock_stream ... PacketReader<MockPacketStream> reader(&mock_stream); ... exercise reader ...