WillReturn Behavior

Top  Previous  Next

To return a specific value from a faked method, simply use CallTo combined with WillReturn. This allows you to define the behavior of the faked method and specify the return value.

 

Examples

 

 

TEST_F(Examples, ChangeReturnValue)

{

   // Arrange

   auto a = Isolator();  

   Person* fakePerson = a.Fake.Instance<Person>();

   

   a.CallTo(fakePerson->GetAge()).WillReturn(10);

 

   // Act

   auto result = fakePerson->GetAge();  

 

   // Assert

   ASSERT_EQ(10result);

}

 

 

You can also fake methods that return non-trivial types, such as strings. Here's an example of faking a method that returns a string:

 

TEST_F(Examples, ChangeStingReturnValue)

{

   // Arrange

   auto a = Isolator();  

   Person* fakePerson = a.Fake.Instance<Person>();

   

   a.CallTo(fakePerson->GetTransportName()).WillReturn(string("Bus"));

 

   // Act

   // continue will test...

}

 

 

In some cases, you might need to return objects from faked methods, either by reference or by value. Here's how you can return an object by value:

 

TEST_F(Examples, ReturnLocations)

{

   // Arrange

   auto a = Isolator();  

   GPSLocation testLocation = GPSLocation (1, 1);

   Person realPerson = Person();

 

   vector<GPSLocation> testStopsVector;

   testStopsVector.push_back(GPSLocation(0, 0));

   testStopsVector.push_back(testLocation);

   testStopsVector.push_back(GPSLocation(2, 2));

 

   auto fakeTransport = a.Fake.Instance<ITransport>();

   a.CallTo(fakeTransport->GetAllStops()).WillReturn(testStopsVector);

 

   realPerson.SetTransport(fakeTransport);

 

   // Act

   auto result = realPerson.TransportStopsAt(testLocation);  

 

   // Assert

   ASSERT_TRUE(result);

}

 

Note: In order to return by value, Typemock utilizes copy, default constructors or assignment operators to replicate values.
If it cannot find those, it uses shallow copy instead.

 

Note: There are times that the compiler optimizes out the constructors if they are not used, and Isolator++ won't be able to find them and call them (and will perform a shallow copy).
In order to force the compiler to create the method so it can be faked use: Testable.Members<> as follows:

 

 

auto a = Isolator();  

a.Testable.Members<ReturnedClass>();

 

a.CallTo(fake->GetReturnedClass()).WillReturn(myReturnClass); // Returned by value

 

 
 

Note: To fake Microsoft classes or if your methods return Microsoft types, download the PDB file from the Microsoft Server (See Local Debug Symbols)

 

 

 


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