DoInstead behavior

Top  Previous  Next

Isolator++ Professional allows you to replace behavior of existing method, by specifying an alternative implementation. If none of the Return methods work, this mechanism allows you to specify the exact behavior you need.

 

The DoInstead methods can be specified on static, global or instance methods.

You can do this using:

 

 

WHEN_CALLED(function).DoStaticOrGlobalInstead(function, Context)

 

 

and

 

 

WHEN_CALLED(function).DoMemberFunctionInstead(instance,function)

 

 

Example

 

Assuming the following class is in the production code:

 

class Person

{

private:

   static int groupID;

public:

   int GetAge() { return 0; }

   static int GetAverageAge() { return 0; } 

   static bool IsPartOfGroup(int newGroupID) { return false; }

};

 

Let's replace the implementation of GetAge with our own implementation.

To do that, we'll create a function that will replace the original, in our own class (could also be the test class):

 

class AltPerson

{

public:

   int ReturnAnotherAge() { return 10; }

   static int ReturnAnotherAverageAge() { return 20; } 

};

 

Note: The signature and calling convention of the replacing method should match the original method. When changing behavior of instance methods, you should use an instance method replacement:

 

TEST_F(Examples, DoInsteadForInstanceMethod)

{

   Person* livePerson = new Person();        

   AltPerson* altPerson = new AltPerson();

   

 

   WHEN_CALLED(livePerson->GetAge()).DoMemberFunctionInstead(altPerson,ReturnAnotherAge);

 

   ASSERT_EQ(10, livePerson->GetAge());

 

   ISOLATOR_CLEANUP();

}

 

 

The two arguments sent to DoMemberFunctionInstead are the replacement instance and the replacing method (no parenthesis).

 

Replacing static or global calls

 

TEST_F(Examples, DoInsteadForStaticMethod)
{

   WHEN_CALLED(Person::GetAverageAge())

 .DoStaticOrGlobalInstead(AltPerson::ReturnAnotherAverageAge , NULL);

 

   ASSERT_EQ(20, Person::GetAverageAge());

 

   ISOLATOR_CLEANUP();
}

 

 

Passing data to static alternative implementation

It is possible to pass extra data to the implementation, you pass the data in the second argument of DoStaticOrGlobalInstead and you grab it using the GET_EXTRA_DATA() macro.

 

Example where we will return the original age if the person is in group 5 or a fake age of 10.

 

 

static int GetAge() 

{

   Person* fakePerson = (Person*)GET_EXTRA_DATA();

   return fakePerson->IsPartOfGroup(5) ? fakePerson->GetAge() : 10; 

}

TEST_F(Examples, DoInsteadForStaticMethod)
{

   Person* fakePerson = FAKE<Person>();

 

   WHEN_CALLED(fakePerson->GetAge())

 .DoStaticOrGlobalInstead(AltPerson::ReturnAnotherAverageAge , fakePerson);

 

   ASSERT_EQ(10, fakePerson->GetAge());

 

   ISOLATOR_CLEANUP();
}


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