Custom Assertions |
Top Previous Next |
To create custom assertions between parameters passed to methods, you can use the CallTo(...).WillDoInstead() combo, and provide your own verification lambda:
Assuming the following class in production code:
class Person { public: int GetAverageChildAge(int child1, int child2) { return (child1 + child2) / 2; } int CallPrivate(int var) { return SomePrivate(var); } private: int SomePrivate(int var){ return var; } int SomePrivate(string var){ return stoi(var); }
};
We'd like to create a custom assertion that GetAverageChildAge actually gets called with the parameters of the same parity, so let's create our verification lambda and use it:
TEST_F(Examples, CustomAssertion) { // Arrange auto a = Isolator(); Person* personPtr = new Person();
a.CallTo(personPtr->GetAverageChildAge(A::Any(),A::Any()).WillDoInstead([](int param1, int param2) { // Assert int mod1 = param1 % 2; int mod2 = param2 % 2; ASSERT_EQ(mod1, mod2); return -1; });
int child1 = 0; int child2 = 3;
// Act // We should get an assert exception since the one arg is even and the other odd personPtr->GetAverageChildAge(child1, child2);
}
For simpler custom assertions on parameters passed to methods, you can use the Conditional Checkers:
TEST_F(Examples, SimpleAssertion) { // Arrange auto a = Isolator(); Person* personPtr = new Person();
a.CallTo(personPtr->GetAverageChildAge(A::Any(),A::Any()).WillBeIgnored();
int child1 = 0; int child2 = 3;
// Act personPtr->GetAverageChildAge(child1, child2);
// Assert a.CallTo(personPtr->GetAverageChildAge(A::Eq(0),A::Le(10)).VerifyWasCalled();
}
Note: In order to assert a specific overload was called with matching arguments, use the A::Matches<> API to specify the overload and the arguments predicate.
TEST_F(Examples, CustomAssertion) { // Arrange auto a = Isolator(); Person* personPtr = new Person();
a.CallTo(personPtr->GetAverageChildAge(A::Any(),A::Any()).WillBeIgnored();
int child1 = 0; int child2 = 3;
// Act personPtr->GetAverageChildAge(child1, child2);
// Assert a.CallTo(personPtr->GetAverageChildAge(A::Eq(0),A::Matches([](int val){return val==2 ;})) .VerifyWasCalled();
}
As in public methods, to assert a private overloaded method with matching arguments was called, use the A::Matches<> API:
TEST_F(Examples, CustomAssertion) { // Arrange auto a = Isolator(); Person* personPtr = a.Fake.Instance<Person>(FakeOptions::CallOriginal);
// Act personPtr->CallPrivate(10);
// Assert a.CallToPrivate(A::Member(personPtr, SomePrivate),A::Matches([](int val){return val==10;})) .VerifyWasCalled();
}
|
Copyright Typemock Ltd. 2009-2025. All Rights Reserved.