WillDoInstead Behavior |
Top Previous Next |
Isolator++ Professional allows you to replace the behavior of existing methods with your own custom implementation. This can be especially useful when you need to specify an alternative implementation for testing purposes, such as applying specific logic that differs from the original method.
The WillDoInstead() method allows you to define a custom behavior using a lambda expression. This enables you to return dynamic values, manipulate arguments, or apply complex logic based on the method's context.
a.CallTo(function).WillDoInstead([](optional-args) { // Custom code })
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.
TEST_F(Examples, DoInstead) { // Arrange auto a = Isolator(); Person* livePerson = new Person();
a.CallTo(livePerson->GetAge()).WillDoInstead([]() {return 10;} );
// Act auto result = livePerson->GetAge();
// Assert ASSERT_EQ(10, result); }
Getting Arg values To use the values of the args sent, define the optional arg types in the custom lambda function:
TEST_F(Examples, DoInstead) // Arrange auto a = Isolator(); Person* livePerson = new Person();
a.CallTo(Person::IsPartOfGroup(A::Any()).WillDoInstead([](int id) {return id>10 ;});
// Act auto result = Person::IsPartOfGroup(11);
// Assert ASSERT_TRUE(result);
Note: The signature of the args inside the the lambda must match the original method. It can have less args if some args are optional. This also helps when refactoring - adding more args does not break the unit tests.
Passing data You can capture data in the lambda to pass it into the method being faked. This allows you to access and use external variables inside your custom implementation.
In the following example, we return the original age if the person is in group 5, and a fake age of 10 otherwise.
TEST_F(Examples, DoInstead) // Arrange auto a = Isolator(); Person* fakePerson = a.Fake.Instance<Person>();
a.CallTo(fakePerson->GetAge()).WillDoInstead([&]() { return fakePerson->IsPartOfGroup(5) ? fakePerson->GetAge() : 10; // Note GetAge() is not faked here });
// Act auto result = fakePerson->GetAge();
// Assert ASSERT_EQ(10, result);
Note: Methods called within the InvokeOriginal are never faked
|
Copyright Typemock Ltd. 2009-2025. All Rights Reserved.