ThrowTheSwitch / CMock

CMock - Mock/stub generator for C
http://throwtheswitch.org
MIT License
653 stars 269 forks source link

Move Expect calls to subfunction #396

Closed ErdlingProductions closed 2 years ago

ErdlingProductions commented 2 years ago

Hello! In order to make tests more readable, I wanted to move setup-Expect calls into a sub-function. Those setup-Expect calls make use of ReturnThruPtr in order to deliver data.

// Prototype:
//
void foo(uint8_t * byte);

Example (this test works):

void
test_...(void)
{
    // Setup:
    //
    uint8_t byte_test = ...;
    foo_ExpectAnyArgs();
    foo_ReturnThruPtr_byte(&byte_test);

    some_func_that_uses_foo_Expect(args_dependent_on_foo);
}

Now if I move the setup to a separate function, the ExpectThruPtr does not provide the data anymore, however compilation does not throw any errors.

void
setup(void)
{
    uint8_t byte_test = ...;
    foo_ExpectAnyArgs();
    foo_ReturnThruPtr_byte(&byte_test);
}

void
test_...(void)
{
    setup();

    some_func_that_uses_foo_Expect(args_dependent_on_foo);
}

Is this supposed to work or is there a reason why it doesn't? Thanks a lot in advance!

mvandervoord commented 2 years ago

The function _ReturnThruPtr is doing exactly that... using a pointer. Unfortunately, with the way you've created this test, you've allowed the data to go out of scope by the time your test needs to use it. This is similar to doing this (which is also invalid C design):

char* getName(void)
{
    char* retval = "Bob";
    return retval;
}

In the example above, if you call getName(), it MIGHT work sometimes and it might not... it really depends on if the compiler has chosen to do something else with the stack space that you had Bob sitting in, because retval is now out of scope.

The solution here is similar. You can add either a const in front of byte_test, add a static in front of byte_test, or you can move byte_test out of the function and make it a module scoped static variable. Any of these will keep the contents in scope and your code will be working again.

ErdlingProductions commented 2 years ago

Hello Mark, I understand. I added static and it works, awesome :) const however did not work for me.

Thanks a lot for your detailed explanation!