ThrowTheSwitch / CMock

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

Check that a mocked variable has been written to #444

Open MikeExMachina opened 1 year ago

MikeExMachina commented 1 year ago

Lets say I have a function in my module like this:

#include "some_file.h"
void func(void){
   x = 5;
   x = 6;
}

where x is declared in some_file.h as so:

   extern uint8_t x;

If I was only writing a single value, say just 5, I could use this pattern:

void test_x_is_set_to_five(){
  x=0;
  func();
  TEST_ASSERT(x==5);
}

But how can I check that it was set to both 5 AND 6 consecutivly? If "some_file.h" provided a setter function instead of direct var access like:

void func(void){
   set_x(5);
   set_x(6);
}

Then I could do:

void test_func_5_AND_6(){
  x=0;
  func();
  set_x_Expect(5);
  set_x_Expect(6);
}

It would be really nice if cmock created expect style functions for header declared variables as well as functions. Is creating shim "setter" functions like above the only way to validate this kind of behavior?

Before someone tells me that providing direct access to vars is bad form and I should be providing api function all the time: This is not a pattern that I use frequently, the one place where it crops up is where the var in question is actually a representation of a hardware register declared in some chip support header that gets automagically defined by the compiler. Specifically I'm working on a PIC32 that requires sequentially writing multiple values to a "SYSKEY" register in order to unlock writing to certain other configuration registers that are otherwise locked and readonly.

mvandervoord commented 1 year ago

Yes it's the only way.

Creating the expect-style interfaces (as you've proposed) wouldn't be hard. Unfortunately, the C language wouldn't allow us to intercept a direct variable assignment in the release portion of the code, so the generated hooks would be useless. We're confined in this case by the limits of the language.