Kane Anderson
Kane Anderson

Reputation: 563

Can I use cmocka to mock a function that returns a struct?

I have a simple structure with two data members.

typedef struct
{
    int32_t x;
    int32_t y;
} MyStructType;

And I have a function that returns the struct by value.

MyStructType get_my_struct(void)
{
    MyStructType test = { 1, 2 };
    return test;
}

So, how can I mock get_my_struct() using cmocka?

I tried

MyStructType get_my_struct(void)
{
    return mock_type(MyStructType);
}

// or

MyStructType get_my_struct(void)
{
    return mock_ptr_type(MyStructType*);
}

but I get compile errors.

I read the cmocka documentation for mock objects, but it didn't give me a clear answer.

Upvotes: 0

Views: 1933

Answers (1)

Kane Anderson
Kane Anderson

Reputation: 563

You can dereference a mocked pointer type,

MyStruct get_my_struct(void)
{
    return *mock_ptr_type(MyStructType*);
}

but you need to make sure will_return() is not NULL.

Upvotes: 0

Related Questions