eranpeer / FakeIt

C++ mocking made easy. A simple yet very expressive, headers only library for c++ mocking.
MIT License
1.22k stars 170 forks source link

Spy some dependencies #328

Closed jim-king-2000 closed 2 months ago

jim-king-2000 commented 3 months ago

Suppose we have a function in my production code.

void ProductionCode()
{
    do1Thing();
    do2Thing();
    do3Thing();
}

Now we need write a unit test for this function. And we want to spy do2Thing() and let it throw an exception. Pseudo-code is like this:

#include "ProductionCode.h"

TEST()
{
    mock("do2Thing", [](){ throw "exception"; });
    ProductionCode();
    mock.assertThrow("exception");
}

Is it possible to do this without changing the source code of ProductionCode?

FranckRJ commented 3 months ago

You can only mock virtual functions. Basically the library works by creating fake objects with an hand-crafted vtable, so when calling a virtual function on that object it will call the mocked function that you defined in your test.