Adam
Adam

Reputation: 532

C unit test framework that supports mocking nested functions

I'm looking for a unit testing framework in C that supports mocking helper functions inside a function.

Example: I have two functions, Function A and Function B both of which are in the same source file. Function B is called from within Function A. I'm looking for a framework that will enable me to mock Function B when called from Function A.

Currently we use cmockery but it does not support this feature.

Any ideas would be great.

Upvotes: 1

Views: 324

Answers (2)

JamesR
JamesR

Reputation: 745

We use Typemock Isolator++ since you don't have to change your production code.

See example:

void FunctionB()
{
            throw "error";
}

void FunctionA()
{
            FunctionB();
}

TEST_CLASS(GlobalCMethods)
{
public:
            TEST_METHOD(MockingGlobalFunction)
            {
                            FAKE_GLOBAL(FunctionB);
                            FunctionA();
            }
};

Upvotes: 4

Aaron Digulla
Aaron Digulla

Reputation: 328754

You can try to use the C preprocessor for this:

CALL(func)(...);

Usually, the macro expands to the argument

#define CALL(f) f

To enable mocking, use

#define CALL(f) mock_##f

Now every function call will be redirected to mock_... which allows you to inject code to divert the call to a mock or the real function.

Upvotes: 1

Related Questions