Faking reference parameters

Top  Previous  Next

When you need to fake methods that return values through out parameters (i.e., values passed by reference), you can use the A::SetOut API.

 

Let’s say we have a Product class method IsExpired that calls the system function GetSystemTime, which fills the SYSTEMTIME struct via an out parameter. We want to fake this system call to return a custom time value.

 

 

bool Product::IsExpired()

{

   SYSTEMTIME now;

 

   ::GetSystemTime(&now);

  

   if (now.wYear > 2012)

   return true;

   return false;

}

 

Here, GetSystemTime is a system function that returns the current date by modifying the now variable.

To test IsExpired without relying on the real system time, we can fake GetSystemTime using A::SetOut.

 

 

TEST_F(IsolatorPPTests, IsExpired_YearIs2013_ReturnTrue)

{

            // Arrange

           auto a = Isolator();  

            Product product;

 

 // Prepare a future time construct

 SYSTEMTIME fakeTime;

 fakeTime.wYear = 2013;

 

 // Fake the GetSystemTime in all DLLs'

 a.Testable.GlobalFunction(GetSystemTime); 

 

 // Replace the returned value when the method is called 

 // with the fake value.

 a.CallTo(GetSystemTime(A::SetOut(fakeTime))).WillBeIgnored();

 

           // Act

           auto result = product.IsExpired();  

 

           // Assert

         ASSERT_TRUE(result);

}

 

 

Because GetSystemTime is a global method, we use Testable.GlobalFunction.

Following that, we use CallTo to ignore the call to GetSystemTime (and not run the regular implementation), and use A::SetOut, to supply our custom return value.

 

When GetSystemTime is called, it returns fakeTime, and IsExpired returns true.

 

 

Reference parameters and private methods
 

A::SetOut works with private methods as well, for example:

 

 

  a.CallToPrivate(A::Global(GetSystemTime),A::SetOut(fakeTime)).WillBeIgnored();

 

 

In some cases Isolator++ Professional is not able to figure out the allocation size of an argument (for example, when the argument is an array). In this case you need to pass a size of an argument to A::SetOut.

 

  

  int fakeArr[5] = {1, 2, 3, 4, 5};

  auto size= sizeof(int) * ARRAYSIZE(fakeArr);

  a.CallTo(person->GetSomeArray(A::SetOut(&fakeArray, size))).WillBeIgnored();

 

 

Note: A::SetOut will work only for WillBeIgnored, WillReturn and WillReturnFake behaviors and only when all conditional behaviors are matched.

 

 


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