Typemock Isolator++ Code Examples You Can Run For C/C++

You will need to set up a unit test project first. You will also find examples you can run under the installation directory of Typemock.

Learn the following examples:

  • Faking Static Methods
  • Creating Recursive Fakes
  • Setting behavior on a chain
  • Faking Live Object
  • Faking “Future” Instances of classes
  • Asserting calls

Faking Static Methods

Faking a static method is easy with Isolator++ Professional.
Suppose we have this class with this simple static method “GetResult”:

The test:
In this test, we create a real object to return and modify its behavior.
We then use WHEN_CALLED on the static factory method to return it:

Creating Recursive Fakes

Recursive Faking is the ability to fake everything you don’t care about.
All methods of the fake will return fakes, and they, in turn, will return fakes, and so on. Doing this with Isolator++ is easy and require only one line:

The test:
In this test, every method in the chain will be mocked. When the chain of method will be called the behavior will be as modified.

Faking Live Object

Live objects are partially real, partially faked. We create

them as regular objects and then use WHEN_CALLED to change part of their behavior.

The test:
In this test, we fake an internal call to a public method. To change that behavior, we use the WHEN_CALLED macro on the object we created.

Faking “Future” Instances of classes

Sometimes, the dependency we want to fake is instantiated inside the class-under-test
We have a Person class with a FillAddressFromDatabase method. When the Address object gets constructed, it accesses the database –
a thing we want to avoid.

Note that the Address object is created inside the constructor. When we run the test, it is created after the method-under-test was
already invoked. We call these objects “future” objects.

The test:
With the FAKE_ALL API, we create a fake address handle, that would be returned whenever a new address is called.
On the handle, we can set behavior. In this test, we test our Person class. We take care of the future Address object, using FAKE_ALL and
Then use WHEN_CALLED to return a fake value. All future objects of the same type will go through the handle. All method calls will
Behave as set by the handle.

Asserting calls

This example will show how to assert a method was called with any value passed to it.

{
public:
void Person::SetAddressCountry(Address* pAddress, string country)

pAddress->SetCountry(country);
};

The test
The test shows the usage of ASSERT_WAS_CALLED macro for a method called on a faked dependency.
If pAddress->SetCountry will not be called Isolator++ will throw a TypemockException.