How-To: Faking Private Methods with Isolator++

In many cases, the dependency we’re trying to get around is not in another class, but in the one we’re trying to test. To make things worse, this method is sometimes inaccessible. When that happens, we need to fake the private method, leaving the rest of the object intact. And we can do this easily with Isolator++.

Let’s look at our Person class. It has this method we’d like to test:

bool Person::IsLivingInSeattle()

{

    if (InternalNumberOfYearsInSeattle() > 0 )

    {

        return true;

    }

    else

        return false;

}

 

int Person::InternalNumberOfYearsInSeattle()

{

    throw ("Not Implemented yet!");

}

The InternalNumberOfYearsInSeattle method is private, and obviously, this is problematic. We’d like to test the IsLivingInSeattle method, but change the behavior of the private method. Here’s our test:

    1 TEST_F(PersonTests, IsLivingInSeattle_InSeattleFor5Years_ReturnsTrue)

    2 {

    3     Person* person = new Person();

    4 

    5     PRIVATE_WHEN_CALLED(person, InternalNumberOfYearsInSeattle).

    6         ReturnVal(5);

    7 

    8     ASSERT_TRUE(person->IsLivingInSeattle());

    9     ISOLATOR_CLEANUP();

   10 }

  • Line 3: We’re creating a person object. This is a “live” object – a regular object, which we’re going to change the behavior of.
  • Line 5, we’re using PRIVATE_WHEN_CALLED. This macro takes two arguments: the object pointer, and the method name (without parenthesis).
  • Line 6: We change the method behavior to return the value we want.
  • Line 9: We do some cleanup.

And that’s it. We changed the behavior of the private method, and when the public method runs, it calls it, gets the faked value and continues.

Stay tuned for more Isolator++ examples. Or better yet, try it for yourself!

Gil Zilberfeld