Assert the count of method calls

Top  Previous  Next

Sometimes, asserting that a method was called is not enough, and you want to assert it was called a specific number of times. For this, you'll use the TIMES_CALLED macro. Let's look at an example.

 

 

TEST_F(Examples, NumberOfCountedCalls)

{

 Person* fakePerson = FAKE<Person>();

 fakePerson->GoToWork();

 fakePerson->GoToWork();

 

 int num = TIMES_CALLED(fakePerson->GoToWork());

 ASSERT_EQ(2, num);

 

 ISOLATOR_CLEANUP();

}

 

In this example, we want to assert that the GoToWork method was called twice. The TIMES_CALLED macro returns the number of occurrences of the method calls. Once we have this number, we can assert equality to 2.

 

What about Live Instances?

 

When working with live instances, you'll need to tell Isolator++ Professional to specify a method by using WHEN_CALLED on it, if you'd still like to perform the original method, just do the WHEN_CALLED->CallOriginal combo:

 

TEST_F(Examples, NumberOfCountedCalls)

{

 Person* person = new Person();

 WHEN_CALLED(person->GoToWork()).CallOriginal(); \\you can also use .Ignore or any other behavior.

 

 person->GoToWork();

 

 int num = TIMES_CALLED(fakePerson->GoToWork());

 ASSERT_EQ(1, num);

}

 

As with the other assertion macros, ASSERT_WAS_CALLED and ASSERT_NOT_CALLED, we need to call FAKE or set a behavior with WHEN_CALLED at least  once, prior to calling TIMES_CALLED. The same goes to for static methods with FAKE_STATICS.

 

Asserting Private Methods

For private methods use the PRIVATE_TIMES_CALLED API.

For asserting the times an instance method was called:

 

 

int num = PRIVATE_TIMES_CALLED(fakePerson,GoToWork);

 

 

In a similar fashion, a static method can be asserted:

 

 

int num = PRIVATE_TIMES_CALLED(_,Person::GetAverageAge);

 

 

 

{

    TestPrivate *fake = FAKE<TestPrivate>(FakeOptions::CallOriginal);        

    fake->SetPrivate(2);

 

    PRIVATE_ASSERT_WAS_CALLED(fake, PrivateMethod, TYPEOF(PCSTR), TYPEOF(UINT));

    PRIVATE_ASSERT_NOT_CALLED(fake, PrivateMethod);

    PRIVATE_ASSERT_NOT_CALLED(fake, PrivateMethod,TYPEOF(int));

}

 

 

Asserting overloaded private methods

To specify an overloaded method by passing the types of the arguments using TYPEOF(Type) macro.
 

 

PRIVATE_TIMES_CALLED(person, CanPing, TYPEOF(bool));

 


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