Assert the count of method calls

Top  Previous  Next

Sometimes, verifying that a method was called isn't enough—you need to confirm it was called a specific number of times. Isolator++ Professional provides the GetTimesCalled API for this purpose.

 

Example: Counting Calls on Fake Instances

To assert that a method was called a specific number of times:

 

TEST_F(Examples, NumberOfCountedCalls)

{

   // Arrange

   auto a = Isolator();  

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

 

   // Act

   fakePerson->GoToWork();

   fakePerson->GoToWork();

 

   // Assert

   int count a.CallTo(fakePerson->GoToWork()).GetTimesCalled();

   ASSERT_EQ(2, count);

}

 

GetTimesCalled returns the number of times the method was called.

You can then assert that the count matches the expected number.

 

Asserting Live Instances

 

When working with live instances, you need to set up behavior using CallTo beforehand. If you want the original method to execute, combine CallTo with WillCallOriginal:

 

TEST_F(Examples, NumberOfCountedCalls)

{

   // Arrange

   auto a = Isolator();  

   Person* person = new Person();

   a.CallTo(fakePerson->GoToWork()).WillCallOriginal();

 

   // Act

   fakePerson->GoToWork();

 

   // Assert

   int count a.CallTo(fakePerson->GoToWork()).GetTimesCalled();

   ASSERT_EQ(1, count);

}

 

As with the other assertion API, VerifyWasCalled and VerifyWasNotCalled, we need to call Fake.Instance or set a behavior with CallTo at least once, prior to calling GetTimesWasCalled. The same goes for static methods with Fake.Statics.

 

Asserting Private Methods
 

For private methods, use the CallToPrivate and GetTimesWasCalled combo.

 

Instance methods:

 

 

int num = a.CallToPrivate(A::Member(person, GoToWork)).GetTimesCalled();

 

 

Static methods:

 

 

int num = a.CallToPrivate(A::Global(Person::GetAverageAge)).GetTimesCalled();

 

 

 

Asserting overloaded private methods

 

To count calls to an overloaded private method, specify argument types using the A::Type<type> API:
 

 

int num = a.CallToPrivate(A::Member(person, CanPing),A::Type<bool>().GetTimesCalled();

 


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