In an 8bit mcu, I wrote a piece of code of a state machine using a function pointer static void (*state)(void);
.
Inside the same compilation (let's say sm.c
) unit I implement all the available states.
static void state_foo(void)
{
//execute code
//check results and change state
//state = new_state
}
static void state_bar(void)
{
//execute code
//check results and change state
//state = new_state
}
The state
pointer is dereferenced inside another function in order to be able to call its current state.
void run(void)
{
*state();
}
sm.h
#ifndef _SM_H_
#define _SM_H_
void run(void);
#endif
And finally, the function run()
is called inside main()
.
#include "sm.h"
int main(void)
{
//other functions
while(true) // super loop
{
run()
}
}
So, apart from the run()
function, outside of the module, I do not have access to any of the globals inside the compilation unit of the state machine.
How can I unit test simple state machines like that?
Inside each state I call functions from another modules that do something and check for results for example check for arrays' values, statuses etc... The state changes upon those decisions.
I can isolate the other modules that get called inside my state machine module. But how can I check for the results without having to add multiple printf
functions inside each state? I was thinking of reconstructing the state signatures so they can return a result int
that corresponds to each of the available states so the main()
function be able to know which state is about to get invoked next etc...
Any ideas on that approach?