Faking "future" instances of classes |
Top Previous Next |
In some cases, the dependency you want to fake is instantiated inside the constructor or method of the class-under-test. These instances, created during the execution of the test, are referred to as future instances. To fake such dependencies, Isolator++ Professional provides the Fake.All API.
Consider a Person class that creates an Address object within its constructor. The Address object interacts with the database, which we want to avoid during testing.
{ private: Address* address; public: Person() { address = new Address(); } char* GetCity() {return address->GetCity();}
}
Here, the Address object is created after the Person constructor is called, making it a future instance. To intercept and fake the Address object, we use the Fake.All API. This creates a fake handle for all future Address instances, allowing us to define custom behavior. TEST_F(PersonTests, FakeAddress) { // Arrange auto a = Isolator(); auto addressHandle = a.Fake.All<Address>();
Person person;
a.CallTo(addressHandle->GetCity()).WillReturn("NYC");
// Act auto result = person.GetCity();
// Assert ASSERT_EQ("NYC", result); }
Explanation:
1. Intercepting Future Instances: The a.Fake.All<Address>() call creates a fake handle that controls all future instances of Address. 2. Defining Behavior: Use CallTo on the fake handle (addressHandle) to define behavior for methods of Address. 3. Testing the Class-Under-Test: When the Person constructor creates an Address object, Typemock intercepts the instantiation and replaces it with a fake Address controlled by the handle. 4. Behavior Across Instances: All future Address objects created during the test will follow the behavior defined by the fake handle.
It is possible to set a different default behavior of the future fakes by using the Fake.All<>(FakeOption::<option>), see Setting Default Behavior. |
Copyright Typemock Ltd. 2009-2025. All Rights Reserved.