eranpeer / FakeIt

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

Is it possible to mock just a function? #91

Closed brunohkbx closed 7 years ago

brunohkbx commented 7 years ago

Lets say that I have the following function:

int add(x, y)
{
    return x + y;
}

Is it possible to mock the result? All examples that I saw in examples was required an interface.

// Instantiate a mock object.
Mock<SomeInterface> mock;

// Setup mock behavior.
When(Method(mock,foo)).Return(1); // Method mock.foo will return 1 once.
eranpeer commented 7 years ago

No, Fakeit manipulates the virtual table. It can only​ mock a class.

dolfandringa commented 4 years ago

There is a way to make it work though by creating a class that you can mock/stub, and make fake versions of the functions to test that call that class. Here is a sample. please comment if I have overlooked something.


struct MockFunctions {
    virtual int add(int x, int y) = 0;
    virtual int sub(int x, int y) = 0;
}

Mock<MockFunctions> FakeFunctions;
MockFunctions* pFakeFunctions;

MockFunctions* getFakeFunctionsInstance() {
    //Get a singleton FakeFunctions
    if(!pFakeFunctions) {
        pFakeFunctions = &FakeFunctions.get();
    }
    return pFakeFunctions;
}

int add(int x, int y) {
    return getFakeFunctionsInstance()->add(x, y);
}

int sub(int x, int y) {
    return getFakeFunctionsInstance()->sub(x, y);
}

When(Method(FakeFunctions, add)).AlwaysReturn(10);
TEST_ASSERT_EQUAL(add(5, 6), 10));