简体   繁体   中英

Can I get away with not mocking all methods in an interface in C++ when using googlemock

I am using Google Mock 1.6 RC and am trying to Mock a COM Interface . There are close to 50 methods in the COM Interface some of which are inherited from base interfaces. When I create a mock struct that inherits from this interface and mock only the methods I am using, I get the cannot instantiate abstract class error.

I want to know if it is possible to do this in googlemock or not.

It is not possible to do. You have to overload all pure virtual methods from all interfaces (except for the constructor and destructor).

You have to override every method that has been declared as pure virtual in the classes you inherit from, directly or indirectly. There are two reasons not to want override them all:

  1. There are too many of them and you have something better to do with your time than to go over them all.
  2. Compiling a mock class with all of them mocked out is too slow and takes too much memory.

The fix for (1) is to use the gmock_gen.py script in Google Mock's scripts directory. It goes over the class definition and converts method declarations into the MOCK_METHOD statements. If you have problems with (2), you can replace the unnecessary MOCK_METHOD statements with stubs:

MOCK_METHOD1(f, bool(int i));

with

virtual bool f(int i) {
  thrown std::exception("The stub for f(int) has been invoked unexpectedly.");
}

Throwing an exception will alert you to a situation where a particular stub has been invoked, meaning you likely need to mock it instead.

Edit: If the original interfaces to mock are written using Microsoft's macros, this thread has a script posted that converts them to C++ acceptable to gmock_gen.py .

I'm not entirely sure whether all methods should be covered in the mock class... In the gmock examples you can see that for example destructors are not mocked. Therefore I presume there is no need to mock the entire class.

Anyway, shouldn't you create mock class rather than mock struct?

However, there is a gmock_gen.py tool in scripts/generator that should do the hard work of mocking large classes for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM