Faking live instances |
Top Previous Next |
You can use the a.CallTo API to change the behavior of a method in a live (unfaked) object. This allows you to isolate specific parts of the code under test without fully faking the object itself.
Consider the following Person class:
class Person { public: Address* FillAddress() {return Address::GetFromDatabase();} int GetHouseNumber() { FillAddress()->GetHouseNumber();} ... }
In this example:
- The FillAddress method interacts with the database to fetch an Address object. - We want to test the GetHouseNumber method without accessing the database.
To test that the GetHouseNumber method works and returns the default value 1 without accessing the database, we fake only the behavior of the FillAddress method. In this case we do so to return a fake Address.
TEST_F(PersonTests, DefaultHouseNumberIs1) { // Arrange auto a = Isolator(); Person* person = new Person();
// Change behavior of a live object a.CallTo(person->FillAddress()).WillReturn(new Address("Oxford",1));
// Act auto result = person->GetHouseNumber();
// Assert ASSERT_EQ(1, result); delete person; }
Note that we're creating the Person object with a regular new. It's a standard Person object (not a fake). We then use the same CallTo syntax to ignore the FillAddress call.
|
Copyright Typemock Ltd. 2009-2025. All Rights Reserved.