Faking private and protected methods
|Top Previous Next|
Sometimes you'd like to test code that calls internally a private method, and you'd like to fake that private method.
Change the behavior of a private method of our class
To change the behavior of PrivateMethod, for example to throw an exception, we would write the following:
We use the PRIVATE_WHEN_CALLED macro on the live instance to declare the behavior we want. In this case, we're throwing an exception with a string.
Using this macro has a future-benefit: If in the future you decide to expose the PrivateMethod as public, the tests still work!
What if we had a private static method, like StaticPrivateMethod was ? The same applies. Simply supply the static method signature too:
As with the instance behavior setting, if the method goes public, it will continue to work.
Change the behavior of a static C function
Static c functions are visible only within the specific module they are defined in. To fake these functions simply pass the static function:
How to change behavior of private method with an out parameters see here.
To fake a specific overload of a private method, see Faking Overloaded methods.
Copyright Typemock Ltd. 2009-2020. All Rights Reserved.