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:
Example: Consider a Person class where the Init() method is called within 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 Person:
TEST_F(PersonTests, FakeMethodInConstructor) { // Arrange auto a = Isolator(); // Fake all Persons, but call the real method, we get a handle Person* personHandle = a.Fake.All<Person>(FakeOptions::CallOriginal);
// Fake Init method that will be called in constructor a.CallToPrivate(A::Member(personHandle,Init)).WillBeIgnored();
// Create a new person, the Init will not run Person person; // Continue with test... }
Note: You can also use Invoke(A::Ctor()) 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 = a.Fake.Instance<Person>(); // Call constructor, Init is Faked by default, you can change any behavior before calling the constructor a.Invoke(A::Ctor(fakePerson)); // Continue with test... }
See the InvokeOriginal API for more information. |
Copyright Typemock Ltd. 2009-2025. All Rights Reserved.