Faking private and protected methods |
Top Previous Next |
Sometimes, you need to test code that internally calls private methods, and you want to control or fake those private methods during testing. Isolator++ provides the CallToPrivate API to help you fake private methods, even if they are not directly accessible.
The following APIs are used to define the private method to be faked: (ICallContext)
The API can be used like this:
a.CallToPrivate(private_method, args...).<behaviour>;
Change the behavior of a private method
class MyClass { private: int PrivateMethod() { return -1; }
To change the behavior of PrivateMethod, for example to throw an exception, we would write the following:
// Arrange auto a = Isolator();
MyClass* myClass = new MyClass();
PCSTR szMessage = "PrivateMethod was called";
a.CallToPrivate(A::Member(myClass, PrivateMethod)).WillThrow(szMessage);
In this example: 1. We use a.CallToPrivate(A::Member(myClass, PrivateMethod)) to fake the private method. 2. We specify the behavior WillThrow(szMessage) to throw an exception when the private method is called. 3. This approach is refactor-safe; if PrivateMethod is later made public, the test will still work.
Here is another example where we fake a local instance while using & in A::Memeber:
// Arrange auto a = Isolator();
MyClass myClass = MyClass();
a.CallToPrivate(A::Member(&myClass, PrivateMethod)).WillReturn(10);
Change the behavior of a private static method
To fake a private static method, you use A::Global. For example, if MyClass has a private static method StaticPrivateMethod, you can fake it as follows: (see Conditional Behavior)
a.CallToPrivate(A::Global(MyClass::StaticPrivateMethod) ,A::Any()).WillThrow(szMessage);
As with the instance behavior setting, if the method is refactored to be public, it will continue to work.
Change the behavior of a static C function (Free Function) Static c functions are visible only within the specific module they are defined in. To fake these use A::Global:
a.CallToPrivate(A::Global(staticFunctionInModule)).WillReturn(20);
Mock Methods Defined in a Specific Module
It is possible to tell Isolator++ to find a private method defined in a specific dll. This is great for performance and if there are methods with the same name and the symbol is not directly referenced in the test executable. To do this use the From API used in A::Member().From("module"), A::Global().From("module") and A::Ctor().From("module")
a.Variable.Set(A::Global(g_staticPrivateVal).From("MyModule.dll"), true);
Out Parameters To change behavior of private method with an out parameters use A::SetOut(), see here.
Faking a specific overloaded method To fake a specific overload of a private method, see Faking Overloaded methods.
|
Copyright Typemock Ltd. 2009-2025. All Rights Reserved.