To make EXPECT_CALL scoped in Google Test, you can use the following methods:
1. Using Braces to Create a Scope
You can create a new scope using braces to limit the lifetime of the expectation.
TEST(MyTest, ScopedExpectations) {
MockClass mock;
{
EXPECT_CALL(mock, Method()).Times(1);
// Code that should satisfy the expectation
mock.Method();
} // Expectation is verified and cleared here
// New scope with different expectation
{
EXPECT_CALL(mock, Method()).Times(2);
// Code that should satisfy the new expectation
mock.Method();
mock.Method();
}
}
2. Using Mock::VerifyAndClearExpectations()
You can manually verify and clear expectations on a mock object.
TEST(MyTest, ClearExpectations) {
MockClass mock;
EXPECT_CALL(mock, Method()).Times(1);
mock.Method();
Mock::VerifyAndClearExpectations(&mock);
// Set new expectations
EXPECT_CALL(mock, Method()).Times(2);
mock.Method();
mock.Method();
}
3. Using testing::InSequence
While not directly scoping EXPECT_CALL, InSequence ensures that expectations are satisfied in a specific order.
TEST(MyTest, InSequence) {
MockClass mock;
{
testing::InSequence seq;
EXPECT_CALL(mock, Method1()).Times(1);
EXPECT_CALL(mock, Method2()).Times(1);
// Code that should satisfy the expectations in order
mock.Method1();
mock.Method2();
}
}
4. Using a Separate Test
If the expectations are complex or need to be reused, consider splitting them into separate tests.
TEST(MyTest, FirstExpectation) {
MockClass mock;
EXPECT_CALL(mock, Method()).Times(1);
mock.Method();
}
TEST(MyTest, SecondExpectation) {
MockClass mock;
EXPECT_CALL(mock, Method()).Times(2);
mock.Method();
mock.Method();
}
Best Practices
- Use braces to create a new scope when you need to limit the lifetime of an expectation.
- Use
Mock::VerifyAndClearExpectations() when you need to manually verify and clear expectations.
- Consider splitting complex expectations into separate tests for better readability and maintainability.
By using these methods, you can effectively scope EXPECT_CALL in Google Test and make your tests more readable and maintainable.