Faking global methods

Top  Previous  Next

When working with global C functions in Isolator++ Professional, you might encounter multiple copies of the same function within different translation units due to linker optimizations or static linking. This can make function interception inconsistent if only CallTo is used.

The Testable.GlobalFunction API ensures that all copies of the specified global function, such as fopen,are correctly intercepted and faked, preventing unintended calls to the original implementation. Without it, some calls to fopen might still invoke the real function, leading to unintended side effects, such as actual file operations in a unit test.

 

Suppose you want to fake the behavior of the global method fopen to return a specific value. Here's how:

 

 

auto a = Isolator();  

a.Testable.GlobalFunction(fopen); // This is required here as the linker might copy multiple global 

                              // implementations of fopen within your code

a.CallTo(fopen(0,0)).WillReturn(_anotherFile);

:A

 

The Testable.GlobalFunction API causes fopen to return a default value (in this case a valid pointer to fake FILE* struct, see Recursive Fakes), and avoid calls to the original implementation.

 

To return other values combine the CallTo API and WillReturn, to control the return value. (See Behavior Setting for additional behaviors)

 

Note: While Testable.GlobalFunction is safer, using only CallTo can be faster. However, it will fake only the current copy of the global function.

 

Note: When faking a global function that uses templates, you must explicitly specify the template arguments because the compiler cannot infer them automatically when using A::Any().

 

Additionally, if the function has multiple template parameters, meaning there’s a comma inside the <...>, you must wrap the function call in parentheses. This is required because the comma would otherwise be misinterpreted as separating function arguments rather than template parameters.

 

 

TEST_F(FakeGlobalTwoGenerics, FakeGlobalTemplate)

{

    auto a = Isolator();

    // must wrap with () due to the comma in the template <>

    a.CallTo((GlobalFunc<int,double>(A::Any(), A::Any()))).WillReturnFake();

    ASSERT_EQ(0, GlobalFunc(1, 2.0));

}

 


Copyright  Typemock Ltd. 2009-2025.  All Rights Reserved.