EXPECT_CALLs

时间:2017-03-21 22:21:00

标签: c++ googletest googlemock gmock

我试图测试两个串口写+读取调用。第一个必须在read上阻塞101ms,从而导致超时错误。第二个应该运行正常。基于google mock manualInSequence变量应该确保。这是代码:

  {
    // This variable ensures the sequence order
    InSequence s;

    EXPECT_CALL(serial_, Write(_, _))
        .With(ElementsAreArray(command1_))
        .WillOnce(Invoke(Write));

    EXPECT_CALL(serial_, Read(_, _, _))
        .WillOnce(Invoke(TimeoutRead));

    EXPECT_CALL(serial_, Write(_, _))
        .With(ElementsAreArray(command2_))
        .WillOnce(Invoke(Write));

    EXPECT_CALL(serial_, Read(_, _, _))
        .Times(1)
        .WillOnce(DoAll(SetArrayArgument<0>(response_begin, response_end),
                        SetArgumentPointee<2>(response_.size()),
                        Return(true)));
  }

TimeoutRead只是一个导致当前线程休眠101ms的函数。 但是,我不断收到此运行时错误:

[ RUN      ] MasterTest.LostReply
/host/Users/blah/work/bitbucket/master_test.cc:631: Failure
Mock function called more times than expected - returning default value.
    Function call: Read(0x5652c3f31120 pointing to "\xFF\xFF", 4096, 0x7ffda19d2960)
          Returns: false
         Expected: to be called once
           Actual: called twice - over-saturated and active

似乎GTest正在尝试拨打为第二个EXPECT_CALL设计的最后一个read

有没有办法强制执行这一系列的调用?

[这是临时编辑提供的SSCCE,您需要提供答案]
这是SSCCE我希望您能够正确更新以获得您在问题中提到的错误。以下代码适用并通过:

class Serial_
{
public:
    MOCK_METHOD2(Write, void(int* elems, size_t n));
    MOCK_METHOD3(Read, bool(int* elems, int dummy, size_t* n));
};

int command1_[] = {1,2,3};
int command2_[] = {4,5};
std::array<int, 4> response_{{ 6, 7, 8, 9 }};

void testScenario(Serial_& serial_)
{
    int dummy_arr[100];
    size_t dummy_size;
    serial_.Write(command1_, 3);
    serial_.Read(dummy_arr, 123, &dummy_size);
    serial_.Write(command2_, 2);
    serial_.Read(dummy_arr, 123, &dummy_size);
}

bool TimeoutRead(int* elems, int dummy, size_t* n)
{
    return true;
}

void Write(int* elems, size_t n)
{}


TEST(A,A)
{
    Serial_ serial_;

    // This variable ensures the sequence order
    InSequence s;

    EXPECT_CALL(serial_, Write(_, _))
        .With(ElementsAreArray(command1_))
        .WillOnce(Invoke(Write));

    EXPECT_CALL(serial_, Read(_, _, _))
        .WillOnce(Invoke(TimeoutRead));

    EXPECT_CALL(serial_, Write(_, _))
        .With(ElementsAreArray(command2_))
        .WillOnce(Invoke(Write));

    EXPECT_CALL(serial_, Read(_, _, _))
        .Times(1)
        .WillOnce(DoAll(SetArrayArgument<0>(response_.begin(), response_.end()),
                        SetArgumentPointee<2>(response_.size()),
                        Return(true)));

    testScenario(serial_);
}

0 个答案:

没有答案