Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a class with both virtual and non-virtual methods using Google Mock?

I have a class I wish to Mock using Google Mock. My class has BOTH non-virtual and virtual methods. I've been reading through the Google Mock ForDummies and the Google Mock CookBook. The examples and explanations provided by these resources mention classes with either ALL virtual functions, or NO virtual functions, but not one with both. So I have two questions:

(1) Is it possible to mock a class with mixed virtual/non-virtual types?

(2) What method should be used (if question 1 is true) to mock this class, (If question 1 is false) what could be used instead?

A bit of code if it helps:

class Time_Device : public Time_Device_Interface
{   
private:
     ...
     bool read32_irig_data( uint32_t *data_read, uint32_t reg_address);
     bool thread_monitor_irig_changed( irig_callback_t callback );
public:
     ...
     virtual bool set_time( struct time_sample const &time );
     virtual bool get_time( struct time_sample *time );
     virtual bool register_is_connected_notification( 
         irig_callback_t callback );
 };

A wee bit o'background:

I'm trying to use Google Mock with Google Test because I need to mimic hardware returns in a lot of my methods in order to test coverage, etc. I've been able to successfully use Google Test alone to test some of my methods without Mocking them.

I'm developing using Visual Studio 2010, CMake

I'm new to both Google Test and Google Mock

I cannot change the production code.

like image 851
TWhite Avatar asked Aug 01 '14 21:08

TWhite


1 Answers

(1) Is it possible to mock a class with mixed virtual/non-virtual types?

Yes, it is, but you have to take care. In the mocked class, override only virtual methods.

The mock should look like this :

struct Time_Device_Mock : public Time_Device_Interface
{
    MOCK_CONST_METHOD1( set_time, bool(time_sample const &) );
    MOCK_CONST_METHOD1( get_time, bool(time_sample *) );
    MOCK_CONST_METHOD1( register_is_connected_notification, bool(irig_callback_t) );
};

(2) What method should be used (if question 1 is true) to mock this class, (If question 1 is false) what could be used instead?

This question is a bit weird. You said that non-virtual methods are private, therefore you can not access them. That leaves only option to use virtual methods.

That means, create an instance of the mocked class, and pass it to object which is supposed to use it. The method is called dependency injection, and there are several ways to inject dependency.

like image 160
BЈовић Avatar answered Nov 02 '22 11:11

BЈовић