Faking methods called in constructor

Top  Previous  Next

To fake methods that are called in the constructor (without faking the whole constructor itself) use the following pattern.

·Fake a future instance of the class but set the default behavior of said fake to call the original members.
·Fake methods that are called in the constructor
·Create the faked instance.

 

 

Example. For our example we have a Person class with that calls the Init() method in the constructor.

 

class Person

{

private:

   Address* m_address

   void Init() m_address = new Address();}

public:

   Person() { Init(); 

}

 

 

With the FAKE_ALL API, we create a fake Person object, we can then fake the Init() method before instantiating the new Address:

 

TEST_F(PersonTests, FakeMethodInConstructor)

{

   // Fake all Persons, but call the real method, we get a handle 

   Person* fakePerson = FAKE_ALL<Person>(FakeOptions::CallOriginal);

   // Fake Init method that will be called in constructor 

   PRIVATE_WHEN_CALLED(fakePerson,Init).Ignore(); 

 

   // Create a new person, the Init will not run

   Person person;

   // Continue with test...

}

 

 

Note: You can also use ISOLATOR_INVOKE_CONSTRUCTOR after you setup the Fake, to do the same:

 

TEST_F(PersonTests, FakeMethodInConstructor)

{

   // Fake a Person, all methods are fake, constructor is not called

   Person* fakePerson = FAKE<Person>();

   // Call constructor, Init is Faked by default, you can change any behavior before calling the constructor

   ISOLATOR_INVOKE_CONSTRUCTOR(fakePerson); 

 

   // Continue with test...

}

 


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