0

Is there a clean and easy way to mock non-virtual methods in c++ with gtest ? Despite using the GoogleMock way that force you to re-declare your mocked class.

This feature is essential in my point of view to enable the full potential of BDD, TDD and mocking in c++. I'm using FakeIt currently but I'm still encountering those difficulties :

  • Testing code without having to use virtual methods
  • Testing legacy code without impacting the current code

Edit : I found Injector++ and isolate++ that seems to be great solutions but not cross-plateform.

Alaenix
  • 83
  • 6
  • 1
    _"In this case, instead of sharing a common base class with the real class, **your mock class will be unrelated to the real class**, but contain methods with the same signatures. "_ - this is the _de facto_ way to mock non-virtual methods with Google Test/Mock. You could always write a generator for the mocked class, ideally based on reading the header of the class to be mocked e.g. using LLVM tools. – dfrib Jul 07 '20 at 11:48
  • Another (imo worse) alternative is to using a macro, say `MOCKABLE`, that expands to nothing (empty) in release builds, but to `virtual` when you build your product for test, and use this to mark non-virtual methods you'd like to be easily mockable whilst in testing (note though that this would mean that you would actually be testing a different product implementation in test than in release). – dfrib Jul 07 '20 at 11:51
  • Thanks for your respond. I'm more looking for a developer-friendly solution like [Injector++](https://github.com/mazong1123/injectorpp) or [isolate++](https://www.typemock.com/isolatorpp-product-page/). – Alaenix Jul 07 '20 at 12:54
  • They seem to offer nice syntactic sugar for injections, but as for Gtest: no, this kind of brief solutions do not exist there (for non-virtual or static methods). – dfrib Jul 07 '20 at 13:25
  • Does not yet integrate with gtest, but you might take a look at my PowerFake, introduced here: https://stackoverflow.com/a/48682345/3936307 – hedayat Jan 28 '22 at 11:17
  • 1
    Update: Well, I finally put some time and added support for gmock too. Now it can be used with both gMock and FakeIt. But well, it only works with gcc & clang. – hedayat Jan 31 '22 at 09:34

0 Answers0