Question

I have a small class:

struct Command
{
    uint8_t cmdId;
    uint8_t len;
    uint8_t payload[MAX_PAYLOAD];
};

And I want to verify only the first two elements of the payload using a googlemock expectation. I can't use ElementsAreArray because that checks that the lengths of the payload and the expectation are the same. So far I have an expectation that looks like this:

Command cmd;
cmd.cmdId = 0xD3;
cmd.len = 2;
cmd.payload[0] = 'm';
cmd.payload[1] = 'l';

EXPECT_CALL(mockQueue,
        sendFromIsr(Pointee(AllOf(
                Field(&Command::cmdId, Eq(0xD3)),
                Field(&Command::len, Eq(2)),
                //Field(&BirdCommand::payload, ElementsAreArray(cmd.payload, 2)) !<-- Doesn't work
        ))))
        .WillOnce(Return(true));

Any ideas? The mock class looks like this:

template <typename T>
class MockQueue : public Queue<T>
{
public:
    MOCK_METHOD1_T(sendFromIsr, bool(T &item));
};
Was it helpful?

Solution 2

I have received this solution from Piotr Gorak via the googlemock mailing list, discussion here.

MATCHER_P2(CheckFirstTwo, first, second, "Checks the first two elements of an array")
{
    return arg[0] == first && arg[1] == second;
}

And in the test I verify like this:

EXPECT_CALL(mockQueue, sendFromIsr(
        Pointee(AllOf(
            Field(&BirdCommand::cmdId, Eq(0xD3)),
            Field(&BirdCommand::len, Eq(2)),
            Field(&BirdCommand::payload, CheckFirstTwo('m', 'l'))
        ))
));

I like this solution the most because it does not require me to over-specify the test or zero initialize the data structure in my production code unnecessarily.

OTHER TIPS

What is wrong with this :

EXPECT_CALL( mockQueue, sendFromIsr( Ref( cmd ) )
        .WillOnce( Return( true ) );

?

Since the Command is POD, it should work even if it copies the command (which it doesn't in this case).


EDIT

Since the Command is POD, you need to zero initialize it (or clear the memory occupied by such object when you create it. In your example :

Command cmd = Command();

Then your object will not be uninitialized and the comparison should not fail.

Have you tried

EXPECT_CALL(mockQueue,
        sendFromIsr(Pointee(AllOf(
                Field(&Command::cmdId, Eq(0xD3)),
                Field(&Command::len, Eq(2)),
                Field(&Command::payload[0], Eq('m')),
                Field(&Command::payload[1], Eq('l'))
        ))))
        .WillOnce(Return(true));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top