Unit-Testing Frameworks: GMock

Let's learn about adopting a unit-testing framework called GMock.

Writing true unit tests is about executing a piece of code in isolation from other pieces of code. Such a unit is understood as a self-contained element, either a class or a component. Of course, hardly any programs written in C++ have all of their units in clear isolation from others. Most likely, our code will rely heavily on some form of association relationship between classes. There's only one problem with that: objects of such a class will require objects of another class, and those will require yet another. Before we know it, our entire solution is participating in a "unit test." Even worse, our code might be coupled to an external system and be dependent on its state—for example, specific records in a database, network packets coming in, or specific files stored on the disk.

Test doubles

To decouple units for the purpose of testing, developers use test doubles or a special version of classes that are used by a class under test. Some examples include fakes, stubs, and mocks. Here are some rough definitions of these:

  • A fake is a limited implementation of some more complex class. An example could be an in-memory map instead of an actual database client.

  • A stub provides specific, canned answers to method calls, limited to responses used by tests. It can also record which methods were called and how many times this occurred.

  • A mock is a bit more extended version of a stub. It will additionally verify if methods were called during the test as expected

Get hands-on with 1200+ tech skills courses.