Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods Faking private and protected methods

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

 

class __declspec(dllexport) MyClass

{

private:

   int PrivateMethod() { return -1; }

 

To change the behavior of PrivateMethod, for example to throw an exception, we would write the following:

 

 

#include "MyClass.h"

 

MyClass* myClass =  new MyClass();

 

PCSTR szMessage = "PrivateMethod was called";

PRIVATE_WHEN_CALLED(myClass, PrivateMethod).Throw(szMessage);

 

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!

 

Change the behavior of a private static method

 

What if we had a private static method, like StaticPrivateMethod was ? The same applies. Simply supply the static method signature too:

 

 

PRIVATE_WHEN_CALLED(_, MyClass::StaticPrivateMethod).Throw(szMessage);

 

 

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:

 

 

PRIVATE_WHEN_CALLED(_, staticFunctionInModule).Throw(szMessage);

 

 

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-2023.  All Rights Reserved.