Faking "future" instances of classes

Top  Previous  Next

Sometimes, the dependency we want to fake is instantiated inside the class-under-test. Let's look at an example.

We have a Person class with a FillAddressFromDatabase method. When the Address object gets constructed, it accesses the database - thing we want to avoid in our test.

 

 
class Person

{

private:

   Address* address;

public:

   Person() { address = new Address(); 

   char* GetCity() {return address->GetCity();}

  

}

 

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.

 

So how do we fake the Address object?

 

With the FAKE_ALL API, we create a fake Address handle, that would be returned whenever a new Address is called. And on the handle, we can set behavior. For example:

 

TEST_F(PersonTests, FakeAddress)

{

   Address* fakeAddress = FAKE_ALL<Address>();

   Person person;

   

   WHEN_CALLED(fakeAddress->GetCity()).Return("NYC");

 

   ASSERT_EQ("NYC", person.GetCity());

}

 

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.

 

To set the behavior of a fake object by using the FAKE_ALL<>(Behavior), check Setting Default Behavior.


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