Faking members and local variables |
Top Previous Next |
When a class contains non-pointer object members created internally, you can use the Fake.All API to control the behavior of these objects. This approach allows you to fake specific behaviors of the object's methods without faking the entire class.
Here’s the Person class where the Address object is a direct member (not a pointer):
class Person { private: Address address; public: Person() {} char* GetCity() {return address.GetCity();}
}
To fake the behavior of the address object, follow these steps: 1. Use Fake.All<Address>() to create a fake handle for all future instances of the Address class. 2. Set the desired behavior using CallTo. 3. Create an instance of the Person class. The address member will automatically use the fake.
In our example we create a fake Address handle, and we can set behavior for all current Address object. The test looks like this:
TEST_F(PersonTests, FakeAddress) { // Arrange auto a = Isolator(); // Fake all Persons, we get a handle Address* addressHandle = a.Fake.All<Address>(); a.CallTo(fakeAddress->GetCity()).WillReturn("NYC");
// Create a new person, the Address will be a fake Person person;
// Act auto result = person.GetCity();
// Assert ASSERT_EQ("NYC", result); }
Similarly, if your method under-test creates a local variable during its run, use Fake.All API to set its behavior:
int Person::DoSomething() { SomeClass someClass; return someClass.DoSomethingElse(); }
And the test set up might look like this:
TEST_F(PersonTests, FakeAddress) { // Arrange auto a = Isolator(); // Fake all Persons, but call the real method, we get a handle auto someClassHandle = a.Fake.All<SomeClass>(); a.CallTo(SomeClass->DoSomethingElse()).WillReturn(1);
// Act auto result = person.DoSomething();
// Assert ASSERT_EQ(1, result); } |
Copyright Typemock Ltd. 2009-2025. All Rights Reserved.