how to make EXPECT_CALL google test scoped?
- User
how to make EXPECT_CALL google test scoped?
Assistant
In Google Test (gtest),
EXPECT_CALLexpectations are scoped to the test case by default, but sometimes you need more fine-grained control. Here are several ways to manage the scope ofEXPECT_CALL:1. Using InSequence for Ordered Expectations
TEST(MyTest, TestWithSequence) { MockClass mock; { InSequence seq; EXPECT_CALL(mock, Method1()).Times(1); EXPECT_CALL(mock, Method2()).Times(1); } mock.Method1(); mock.Method2(); }2. Manual Scoping with Braces
You can create explicit scopes using braces to limit when expectations are active:
TEST(MyTest, ScopedExpectations) { MockClass mock; { EXPECT_CALL(mock, Method()).Times(1); mock.Method(); // Satisfies the expectation } // Expectation is verified here // New scope with different expectation { EXPECT_CALL(mock, Method()).Times(2); mock.Method(); mock.Method(); } }3. Using Mock::VerifyAndClearExpectations()
This explicitly verifies and clears all 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(); }4. Using StrictMock or NiceMock with Scoped Lifetime
TEST(MyTest, ScopedMock) { { StrictMock<MockClass> mock; EXPECT_CALL(mock, Method()).Times(1); mock.Method(); } // Mock and expectations destroyed here { StrictMock<MockClass> mock; EXPECT_CALL(mock, Method()).Times(2); mock.Method(); mock.Method(); } }5. Using Expectation Objects
You can store expectations and explicitly remove them:
TEST(MyTest, ExpectationObjects) { MockClass mock; Expectation exp = EXPECT_CALL(mock, Method()).Times(1); mock.Method(); // Remove the expectation Mock::VerifyAndClear(&mock); // Or use RetiresOnSaturation EXPECT_CALL(mock, Method()) .Times(1) .RetiresOnSaturation(); }Best Practices
- Use
Mock::VerifyAndClearExpectations()when you need to reset expectations mid-test - Use scoped blocks when you want automatic cleanup at the end of a scope
- Use
RetiresOnSaturation()when an expectation should stop matching after being satisfied - Consider splitting into multiple tests if you have complex scoping needs
The most common and clean approach is using
Mock::VerifyAndClearExpectations()when you need to change expectations during a test, as it's explicit and easy to understand.- Use
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.