ThrowTheSwitch / CMock

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

I need ExpectWithPtr mock (?) #469

Closed parmi93 closed 6 months ago

parmi93 commented 6 months ago

memory_interface.h

void *mem_inf_malloc(size_t size);  //Allocate memory
void mem_inf_free(void *ptr);       //Free memory

tracelog_manager.h

void tracelog_init();
void tracelog_uninit();

tracelog_manager.c

#include "memory_interface.h"
#include "tracelog_manager.h"

static char* print_buffer = NULL;

void tracelog_init()
{
    print_buffer = mem_inf_malloc(1024);  //Allocate 1KB of memory
}

void tracelog_uninit()
{
    mem_inf_free(print_buffer);  //Free print_buffer
    print_buffer = NULL;
}

void tracelog_uninit_should_fail()
{
    char *foo_buffer = "A";
    mem_inf_free(foo_buffer);   //Deallocate a pointer that should not be freed!
}

test_tracelog_manager.c

#include "unity.h"
#include "tracelog_manager.h"

#include "mock_memory_interface.h"

char tmp_buffer[1024];

void setUp(void)
{
}

void tearDown(void)
{
}

void test_if_memory_is_freed() //The test passes (but for the wrong reason)
{
    mem_inf_malloc_ExpectAndReturn(1024, tmp_buffer);
    tracelog_init();

    mem_inf_free_Expect(tmp_buffer);
    tracelog_uninit();
}

void test_tracelog_uninit_should_fail()
{
    mem_inf_malloc_ExpectAndReturn(1024, tmp_buffer);
    tracelog_init();

    tmp_buffer[0] = 'A'; //adding this makes the test pass
    //tmp_buffer[0] = 'B'; //Uncommenting this line the test fails

    mem_inf_free_Expect(tmp_buffer);
    tracelog_uninit_should_fail();
}

What happens is that by calling the mem_inf_free_Expect(tmp_buffer) function, CMock checks that the first byte pointed to by foo_buffer and tmp_buffer are equal, rather than checking that the addresses are equal.

Is there a way to generate a mock like mem_inf_free_ExpectWithPtr(...)?

parmi93 commented 6 months ago

I found a solution here https://github.com/ThrowTheSwitch/CMock/issues/400

Simply add this parameter in Ceedling's project.yml file

:cmock:
  :treat_as:
    void*:    PTR