如何匹配通过引用传递给模拟函数的结构的字段?

问题描述 投票:1回答:1

我有以下结构:

    struct can_frame {
        canid_t can_id;  /* 32 bit CAN_ID + EFF/RTR/ERR flags */
        __u8    can_dlc; /* frame payload length in byte (0 .. CAN_MAX_DLEN) */
        __u8    __pad;   /* padding */
        __u8    __res0;  /* reserved / padding */
        __u8    __res1;  /* reserved / padding */
        __u8    data[CAN_MAX_DLEN] __attribute__((aligned(8)));
    };

我通过引用传递结构到模拟函数:MOCK_METHOD1(write, int(can_frame* frame));

如果传递结构在数据域中有给定的数字,我想匹配:EXPECT_CALL(*canSocketMock_, write(**if the value of can_frame->data[1] is equal to 10, else assert false**))).WillOnce(Return(16));

我试图结合Pointee,Field和ArrayElement匹配器,但未能创建我想要的东西。匹配器的语法对我来说有点混乱。

编辑:测试:

TEST_F(SchunkDeviceShould, applyBreakWritesRightMessage) {
ASSERT_NO_THROW(sut_.reset(new SchunkDevice(
        canSocketMock_, 3)));
can_frame frame;
EXPECT_CALL(*canSocketMock_, write(FrameDataEquals(&frame, 1, CMD_STOP)))).WillOnce(Return(16));
ASSERT_TRUE(sut_->applyBreak());
}

我们称之为的功能:

bool SchunkDevice::applyBreak() {
    can_frame frame;
    frame.can_id = MESSAGE_TO_DEVICE+canID_;
    frame.can_dlc = 0x02;
    frame.data[0] = frame.can_dlc - 1;
    frame.data[1] = CMD_STOP;
    if (int len = socket_->write(&frame) != 16) {
        return false;
    }
    return true;
}

测试结果:

Unexpected mock function call - taking default action specified at:
/home/../SchunkDeviceTests.cpp:47:
    Function call: write(0x7ffc27c4de60)
          Returns: 16
Google Mock tried the following 1 expectation, but it didn't match:

/home/../SchunkDeviceTests.cpp:457: EXPECT_CALL(*canSocketMock_, write(FrameDataEquals(&frame, 1, CMD_STOP)))...
  Expected arg #0: frame data equals (0x7ffc27c4def0, 1, 145)
           Actual: 0x7ffc27c4de60
         Expected: to be called once
           Actual: never called - unsatisfied and active
c++ googletest gmock
1个回答
0
投票

您可以定义custom matcher来检查结构内容。

MATCHER_P2(FrameDataEquals, index, value, "") { return (arg->data[index] == value); }

然后你会像这样使用它:

EXPECT_CALL(mock, write(FrameDataEquals(1, 10))).WillOnce(Return(16));
© www.soinside.com 2019 - 2024. All rights reserved.