To make EXPECT_CALL scoped in Google Mock, you have several approaches depending on what you mean by "scoped":
1. Using InSequence for Scoped Expectations
cpp
TEST(MyTest, ScopedExpectations) {
MockClass mock;
{
InSequence seq; // Creates a scope for ordered expectations
EXPECT_CALL(mock, Method1());
EXPECT_CALL(mock, Method2());
// These calls must happen in order within this scope
}
mock.Method1();
mock.Method2();
}
2. Using Block Scope with Temporary Expectations
cpp
TEST(MyTest, BlockScopedExpectations) {
MockClass mock;
// First scope
{
EXPECT_CALL(mock, Method1()).Times(1);
mock.Method1(); // Satisfies expectation
// Expectation is verified when leaving this scope
}
// Second scope with different expectations
{
EXPECT_CALL(mock, Method2()).Times(2);
mock.Method2();
mock.Method2();
}
}
3. Using WillOnce and WillRepeatedly for Limited Scope
cpp
TEST(MyTest, LimitedScopeExpectations) {
MockClass mock;
EXPECT_CALL(mock, Method())
.WillOnce(Return(1)) // Only for the first call
.WillOnce(Return(2)) // Only for the second call
.WillRepeatedly(Return(0)); // For any subsequent calls
EXPECT_EQ(1, mock.Method());
EXPECT_EQ(2, mock.Method());
EXPECT_EQ(0, mock.Method());
}
4. Manual Verification and Clearing
cpp
TEST(MyTest, ManualScopedVerification) {
MockClass mock;
// Set up expectations for first phase
EXPECT_CALL(mock, Method1()).Times(1);
mock.Method1();
// Verify and clear expectations manually
Mock::VerifyAndClearExpectations(&mock);
// Set up new expectations for second phase
EXPECT_CALL(mock, Method2()).Times(1);
mock.Method2();
}
5. Using Test Fixtures for Scoped Setup/Teardown
cpp
class ScopedMockTest : public ::testing::Test {
protected:
void SetUp() override {
// Setup expectations that apply to the entire test
EXPECT_CALL(mock_, Initialize()).Times(1);
}
void TearDown() override {
// Cleanup happens automatically, but you can add custom logic
Mock::VerifyAndClearExpectations(&mock_);
}
MockClass mock_;
};
TEST_F(ScopedMockTest, TestMethod) {
mock_.Initialize(); // Satisfies SetUp expectation
// Additional test-specific expectations
EXPECT_CALL(mock_, Process()).Times(1);
mock_.Process();
}
6. Using RAII for Scoped Expectations
cpp
class ScopedExpectation {
public:
ScopedExpectation(MockClass& mock) : mock_(mock) {
EXPECT_CALL(mock_, StartOperation()).Times(1);
}
~ScopedExpectation() {
EXPECT_CALL(mock_, EndOperation()).Times(1);
mock_.EndOperation();
}
private:
MockClass& mock_;
};
TEST(MyTest, RAIIScopedExpectations) {
MockClass mock;
{
ScopedExpectation scoped(mock);
mock.StartOperation(); // Satisfies constructor expectation
// EndOperation() expectation set and called in destructor
}
}
The most common and recommended approach is using block scopes (#2) or manual verification (#4) when you need to clearly separate different phases of your test with different expectations.