How-to: Changing Behavior of Static Methods with Isolator++

Isolator++ can change the behavior of methods very easily, without changing the original implementation. When you change the behavior of an instance or a static method, you can do that in different fashions.

We have a Person class. It has a method called IsFromLA we’d like to test:

bool Person::IsLivingInLA()

{

    Address* address = Address::GetAddress();

    if (strcmp (address->GetCity(),"Los Angeles")==0)

    {

        return true;

    }

    else

        return false;

}

Person is dependent on the Address class:

#define CLASS_API __declspec(dllexport)

class CLASS_API  Address

{

private:

    char* city;

 

public:

    void SetCity(char* newCity) {city = newCity;}

    char* GetCity() {return city;}

   

    static Address* GetAddress()

    {

        throw ("Not implemented yet!");

    }

}

As you can see the static GetAddress method throws an exception, and therefore prevents us from testing the IsLivingInLA method. Let’s write a test for the case the person lives in LA:

    1 TEST_F(PersonTests, IsLivingInLA_AddressIsLA_ReturnsTrue)

    2 {

    3     Person person;

    4     Address laAddress;

    5     laAddress.SetCity( "Los Angeles");

    6 

    7     FAKE_STATICS<Address>();

    8     WHEN_CALLED(Address::GetAddress()).ReturnPtr(&laAddress);

    9 

   10     ASSERT_TRUE(person.IsLivingInLA());

   11     ISOLATOR_CLEANUP();

   12 }

  • Line 4-5: We create the replacement LA Address object first.
  • Line 7: We then declare we’re faking the static methods of the Address type using FAKE_STATICS.
  • Line 8: We’re declaring that when the GetAddress method gets called, it will return the LA Address instead of throwing the exception.
  • Line 11: Cleanup all faking definitions, so they won’t leak into the next test.

Let’s look at the other case, where the person is not from LA:

    1 TEST_F(PersonTests, IsLivingInLA_AddressIsNotFromLA_ReturnsFalse)

    2 {

    3     Person person;

    4     Address nyAddress;

    5     nyAddress.SetCity( "New York City");

    6 

    7     FAKE_STATICS<Address>();

    8     WHEN_CALLED(Address::GetAddress()).ReturnPtr(&nyAddress);

    9 

   10     ASSERT_FALSE(person.IsLivingInLA());

   11     ISOLATOR_CLEANUP();

   12 }

In this case we create an Address object that is initialized differently, and we can test that for that scenario, we get back FALSE.

Stay tuned for more how-to’s. Which one would you like to see next?

Gil Zilberfeld

TOP