1

I am unit testing a c++ class and using Google Test and Google Mock frameworks.

For example, I have a class which has non-virtual functions and I want to mock these two functions which have external dependencies. I don't want to change my class A (using gmock template way solution and dependency injection). Below can be two solutions probably:

  1. Simply mock on fly or any other option like we have in Python where we create MagicMock() and patch.
  2. derive non-virtual class from the test class and wrap the non-virtual function by making it virtual in the test class, then call the prod non-virtual function.
class A 
{
  public:
          bool DBConnect(string username);
  private:
          bool someWork(int);
};
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • Didin't try but I read somewhere this is good [FSeam](https://www.fluentcpp.com/2019/07/02/fseam-a-mocking-framework-that-requires-no-change-in-code-part-1/). – Marek R Feb 13 '21 at 20:03
  • [FSeam part 2](https://www.fluentcpp.com/2019/07/05/fseam-a-mocking-framework-that-requires-no-change-in-code-part-2/). – Marek R Feb 13 '21 at 20:12
  • Anyone can please provide some inputs here, Eagerly waiting? – Geeks World Feb 17 '21 at 08:30

1 Answers1

0

No, you can't. You have to make your C++ code testable.

Solutions that work in interpreted languages, such as Python, are not generally suitable for C++. This is mainly because C++ is compiled and lacks native support for reflection.

There may, however, be a solution for your external depedencies. If those are provided through a library, you can use library preloading to use a different implementation for your unit tests.

rveerd
  • 3,620
  • 1
  • 14
  • 30