Faking concrete classes |
Top Previous Next |
With Isolator++ Professional, you can easily fake the behavior of any class, including concrete classes, using the a.Fake API. This allows you to modify or override the behavior of methods without altering the original implementation.
Let's say we want to change the behavior of a concrete method:
class MyClass { int GetResult() { return -1; } }
We'll use a.Fake.Instance to fake all of the methods of an instance.
auto a = Isolator(); auto fakeMyClass = a.Fake.Instance<MyClass>(); a.CallTo(fakeMyClass->GetResult()).WillReturn(10);
Here’s what happens in this example:
1. Faking the Instance: We create a fake object of MyClass using the a.Fake.Instance API. This automatically fakes all methods of the MyClass class. By default: - Methods returning primitive types (e.g., int) return 0. - Methods returning objects return automatically generated fake objects (see Recursive Fakes for more details).
2.Changing Method Behavior: Using the a.CallTo API, we specify that the GetResult() method should return 10 when called.
Note: Isolator++ Professional automatically fakes all the methods in the class hierarchy.
Calling the original constructor
For example if we Fake all the methods of MyClass, but want the constructor to be called.
class MyClass { int m_id;
MyClass(int id) { m_id = id; } }
We'll use the following code:
// Arrange auto a = Isolator(); auto fakeMyClass = a.Fake.Instance<MyClass>();
// Act a.Invoke(A::Ctor(fakeMyClass), 1);
// Assert ASSERT_EQ(1, fakeMyClass->m_id));
Here’s what happens in this example:
1. Faking the Instance: We fake an object of MyClass using the a.Fake.Instance API.
2. Calling the Constructor: The Invoke API is used with A::Ctor() to call the constructor of the fake object. In this case, we pass the argument 1 to the constructor. You can use Invoke to call both public and private constructors.
3. Assertion: After the constructor is called, the m_id member is set to 1, which we verify using ASSERT_EQ.
Note: Invoke(A::Ctor()) can be called only once per object's lifetime.
Additional References: See Faking methods called in constructor for more usages |
Copyright Typemock Ltd. 2009-2025. All Rights Reserved.