Kane
Kane

Reputation: 6260

GMock: Overriding a default expectation

In GMock, is it possible to replace a previously set expectation?

Assume, a test suite has a default expectation for a specific method call, which is what most test cases want:

class MyClass {
public:
    virtual int foo() = 0;
};

class MyMock {
public:
    MOCK_METHOD0(foo, int());
};

class MyTest: public Test {
protected:
    void SetUp() {
        EXPECT_CALL(m_mock, foo()).WillOnce(Return(1));
    }
    MyMock m_mock;
};

TEST_F(MyTest, myTestCaseA) {
    EXPECT_EQ(1, m_mock.foo());
}

This is working fine. Some of the test cases, however, have different expectations. If I add a new expectation, as shown below, it does not work.

TEST_F(MyTest, myTestCaseB) {
    EXPECT_CALL(m_mock, foo()).WillOnce(Return(2));
    EXPECT_EQ(2, m_mock.foo());
};

I get this message:

[ RUN      ] MyTest.myTestCaseB
/home/.../MyTest.cpp:94: Failure
Actual function call count doesn't match EXPECT_CALL(m_mock, foo())...
         Expected: to be called once
           Actual: never called - unsatisfied and active
[  FAILED  ] MyTest.myTestCaseB (0 ms)

I understand why I am getting this. The question is how to cancel the default expectation, if a test case specifies its own? Does GMock allow it or what approaches can I use to achieve the intended behaviour?

Upvotes: 2

Views: 5605

Answers (1)

Rob Kennedy
Rob Kennedy

Reputation: 163277

No, there's no way to clear an arbitrary expectation. You can use VerifyAndClearExpectations to clear all of them, that's probably more than you want. I can think of several alternatives that avoid the issue:

  • You could work around your problem by simply calling m_mock.foo() once in advance, thus fulfilling the initial expectation.

    TEST_F(MyTest, myTestCaseB) {
        EXPECT_CALL(m_mock, foo()).WillOnce(Return(2));
        (void)m_mock.foo();
        EXPECT_EQ(2, m_mock.foo());
    }
    
  • Another alternative is to change the expectation to have it return the value of a variable, then then update the variable prior to the test body, as described in the cookbook under Returning Live Values from Mock Methods. For example:

    void SetUp() {
      m_foo_value = 1;
      EXPECT_CALL(m_mock, foo()).WillOnce(Return(ByRef(m_foo_value)));
    }
    
    TEST_F(MyTest, myTestCaseB) {
      m_foo_value = 2;
      EXPECT_EQ(2, m_mock.foo());
    }
    
  • Yet another alternative is to specify the return value and the count separately.

    void SetUp() {
      ON_CALL(m_mock, foo()).WillByDefault(Return(1));
      EXPECT_CALL(m_mock, foo()).Times(1);
    }
    

    Then, you only need to specify a new return value for the special test:

    TEST_F(MyTest, myTestCaseB) {
      ON_CALL(m_mock, foo()).WillByDefault(Return(2));
      EXPECT_EQ(2, m_mock.foo());
    }
    

Upvotes: 6

Related Questions