Isolator++ Now Supports x64 bit!

Isolator++ for unit testing C/C++ codeIsolator++ gets a lot of attention these days, especially since we’ve added x64 bit support.

One of the feature requests we got was for an API for faking private static methods, while simulating a returned-by-reference parameter. While I can’t use this as a title, I can definitely show you how to do this.

Our example starts with the SithLord class. Our class has a public static method CanAttackJedi that calls a private static method CheckLightSabreStatus. The method CheckLightSabreStatus return the status as an enum by reference. Unfortunately, a wookie stole the lightsaber, as we can clearly see in the class definition:

bool SithLord::CanAttackJedi()
{
    LightSaberStatus saberStatus;
    CheckLightSaberStatus(&saberStatus);

    switch (saberStatus)
    {
    case On:
        return true;
    case Off:
        return false;
    }
}

void SithLord::CheckLightSaberStatus(LightSaberStatus* status)
{
    throw ("A wookie stole my lightsaber!");
}

 

In order to test the static CanAttackJedi method, we’ll fake the private method. In fact, we’d like to test the two cases, as if the lightsaber was actually there.

For that, we’ll need a couple of things: First, a test framework. I’m using MS Test. Next, we’ll need an alternate class. I declare the AlternateLightSaber in the test code. It is going to be used to divert the call from the private faked method. Since I have two cases, I define two methods. Note they are static and have the same signature as the method I’m faking. The very trivial implementation just returns the status I want for each case.

class AlternateLightSabre
{
public:
    static void LightSaberOn(LightSaberStatus* status)
    {
        *status = On;
    }

    static void LightSaberOff(LightSaberStatus* status)
    {
        *status = Off;
    }
};

 

Finally, in I write the test class. In the tests, I use the PRIVATE_WHEN_CALLED macro. Remember that feature request? There’s no specific API for a static version, so I’m using a fake instance of SithLord. It’s a fake, so no harm there. In each test, I use DoStaticOrGlobalInstead with the proper alternate method:

TEST_METHOD(WhenLightSabreIsOn_CanAttackJedi)
{
    SithLord* dummySithLord = FAKE<SithLord>();

    PRIVATE_WHEN_CALLED(dummySithLord, CheckLightSaberStatus)
        .DoStaticOrGlobalInstead(AlternateLightSabre::LightSaberOn, NULL);

    Assert::IsTrue(SithLord::CanAttackJedi());
}

TEST_METHOD(WhenLightSabreIsOff_CannotAttackJedi)
{
    SithLord* dummySithLord = FAKE<SithLord>();

    PRIVATE_WHEN_CALLED(dummySithLord, CheckLightSaberStatus)
        .DoStaticOrGlobalInstead(AlternateLightSabre::LightSaberOff, NULL);

    Assert::IsFalse(SithLord::CanAttackJedi());
}

 

There you go! We can attack a Jedi safely. Now all we need is to find that damn wookie, get our saber and spread some fear across the empire!

*** LEARN how to gain FREEDOM from C/C++ LEGACY CODE: Watch it now! ***

 

TOP