0

我写了一个谷歌测试(使用谷歌模拟)。以下是相关代码:

MockObj * obj = new MockObj ();
MockDI * mock_di = new DI();
MockDIPtr mock_di_ptr(mock_di); // boost shared ptr
Data data; // sort of on array
data.append(1); data.append(2); // Add two entries
EXPECT_CALL(*obj, get_di_ptr()).WillOnce(Return(mock_di_ptr));
EXPECT_CALL(*mock_di_ptr, get_data(_,_)).WillOnce(SetArgReferee<1>(data));
EXPECT_CALL(*obj , enqueue(_)).Times(2);

实际的实现是:

di_ptr->get_data(int, data); // data is updated via reference
for (int i = 0; i < data.size(); ++i)
{
    enqueue(data[i]);
}

基本上,enqueue()应该为数据中的每个条目调用一次。此外,模拟是正常的模拟(不是严格等)

正如预期的那样,当我检查Times(2).

正如预期的那样,当我检查Times(0)or时,这个测试失败了Times(1)

但是,当我检查时,这个测试通过了Times(3)

为什么?我应该怎么做才能检测到这种行为?

4

1 回答 1

2

MockDI * mock_di = new DI(); should probably read MockDI * mock_di = new MockDI(); to make the line EXPECT_CALL(*mock_di_ptr, get_data(_,_)).WillOnce(SetArgReferee<1>(data)); work.

aleguna made a good point. The following simplified experiment yields the error Actual function call count doesn't match EXPECT_CALL(mock, mockMe(_)).... I suggest to debug the method under test and check data.size() after di_ptr->get_data(). Then set a breakpoint in Data::append() and see who adds more elements.

#include "gtest\gtest.h"
#include "gmock\gmock.h"

using ::testing::_;

class Dependency
{
public:
    virtual ~Dependency() {}

    virtual void mockMe(int i);
};

void Dependency::mockMe(int i)
{
}


class MockDependency : public Dependency
{
public:
    MOCK_METHOD1(mockMe, void (int i));
};


class Cut
{
public:
    void testMe(Dependency& dependency);
};

void Cut::testMe(Dependency& dependency)
{
    for (int i=0; i<2; ++i)
    {
        dependency.mockMe(i);
    }
}


TEST(Experiment, VerifyExactCallCount)
{
    MockDependency mock = MockDependency();
    Cut cut;

    EXPECT_CALL(mock, mockMe(_)).Times(3);

    cut.testMe(mock);
}
于 2012-11-23T14:33:42.497 回答