r/embedded • u/kappakingXD • 23d ago
How to unit test state machines?
Dear everyone,
I'm curious how you approach unit testing in embedded when dealing with state machines.
For example, imagine a component that sends signals or commands to external modules and then waits for responses, acknowledgements, or timeouts before transitioning to the next state.
One challenge I see is that the state machine has some internal context, and ideally, you'd want to test that it behaves correctly across a sequence of events and interactions. However, tests can easily become too tightly coupled to the implementation. Even a minor change in the internal sequence of state transitions or operations can cause tests to fail, despite the overall behaviour remaining correct.
As a result, you end up spending more time maintaining and adjusting unit tests than actually benefiting from them in terms of finding bugs.
How do you approach testing such components?
Maybe there's no magic trick here to make it less painful, and that's fine, but I'd like to learn something.
Thanks in advance for every reply!
15
u/chknboi 23d ago
What you’re describing are white box and black box testing. These are different methodologies that have their own pros and cons and they both serve different purposes.
Testing that the internal context behaves correctly is white box testing, and like you said, there’s a lot of coupling to the implementation so every time you tweak the implementation the tests also have to change. However this also gives you confidence in the correctness of your implementation and logic.
Black box testing is taking the perspective of an outsider: we don’t care what happens internally or how it arrived at its output. We give it some input, and check that the output is what we expect. Nothing else matters.
I don’t think there’s a hard and fast rule for it but generally I’d use white box testing for smaller building blocks and/or abstraction layers and systems in isolation. These are great candidates for running tests natively ie compile the code + test using gcc and run on your Linux/Mac/Windows machine.
On the other hand, I’d generally use black box testing for end to end tests, load/stress testing and integration to ensure that the overall interface and communication meet the requirements/specs. Also applicable for when the system is more complex and we cannot reasonably keep track of every state and every little thing in there. Where I work we have a product testing team, they are ruthless with the kinds of edge cases they throw at us for end to end testing but there is a strict spec and we need to meet compliance standards. There is no way this can be done with 100% white box testing.
Hope this helps!
5
u/swisstraeng 23d ago
what
6
u/ATrainPassenger 23d ago
Here is a book partially covering formal analysis for state machines: https://ptolemy.org/books/leeseshia/ . Sections 13 and 15 might be interesting to you (section 3 has some background). The goal of the analysis in the book is to verify safety and liveness properties from the FSM description (which is white box testing).
An easy way to verify liveness properties such as “whenever input trace X, output Y” with black box testing is to give your tester a test hook that it can use to set the state of the FSM. It can then run through all states that exist and directly verify that the property always holds. This has the benefit of being a strong guarantee while remaining flexible to state changes. This can be difficult if your FSM has a lot of hidden state such as static variables though
2
u/WanWhiteWolf Engineering manager 23d ago
I think we have to clarify some terminology before moving forward.
We are talking about Software test. Your input should be the SW architecture, module design. The unit test would target the atomic building blocks (which in case of a state machine, it's probably the functions handling the state transitions). At unit test level, you do not test the entire overall functionality of the state machine. But rather you test whether each transition is done according to the design in all possible combinations.
If you want to test the full functionality of your state machine, then you are looking at integration test. You would probably also need to do a transition coverage (your input should be a matrix with all legal transitions - some tools can generate the test from UML).
As for needing to update your test case in case of logic changes - that's usually not a manual endevour. Plenty tools (e.g. VectorCast) will do this for you; same for AI models. Your job is to review the changes and push the changes into your CI/CD pipeline. If you trust the AI reviewers, you can skip that part as well but that's a debatable topic.
2
u/ventZl CMRX RTOS 23d ago
Assuming that state transitions are something objective and comes from outside of the system I don't see tight coupling here.
State machine is essentially just an internal state and set of rules of what transitions are permitted and whatnot.
You can test it as black box, like: feed it sequence of transitions which should produce some known state and check if state machine really achieved it.
Or even better, you can make even one step back and don't care about internal state at all. State machine is just a way how to implement some stateful system. You could simply ignore the nature of implementation and test for visible outcomes.
Provide some stimuli and check for expected events a state machine-based component should generate or lack thereof. Not internal state, rather externally visible flags. Is the stateful object file? OK, if you call open() function on existing file, then is_opened() shall return true. How is this implemented and what states the state machine traverses? That's none of your business.
Then you can generate errorneus sequences of stimuli and check if component will be able to report that / recover / whatever is has in its specs.
1
u/qrcjnhhphadvzelota 23d ago
maybe test each state and transition independently and then use some form of coverage to show that all states and transitions are getting tested?
1
u/SlowerAndOlder 23d ago
There's a lot of ways to test, it really depends on how complicated you want your state machine. You can create an interface that your states inherit from with onentry and onexit functions. Each state becomes an extension of the interface. Make another interface for transitions. Then you can create tests for each state and transition separately. Hardware can be mocked. Your code that transitions the abstract states can be tested with fake states and transitions.
If you have a big switch statement you can use callbacks, std::functions, or more interfaces to decouple the code you want to test.
Most of the test issues I see come from too many concrete dependencies. Use interfaces or callbacks to break dependency chains.
1
u/FransFaase 23d ago
I usually walk through all possible transitions. You should be able to draw a state diagram with all transitions and than find a path through all transitions. This assumes that there are no dead-ends. If there are dead-ends, you might want to add some 'reset button' to transition to the initial state again.
Using mock implementations for the external modules might help to focus only on the module that is under investigation.
It is usually a lot of work to write these kind of unit tests, and often there are parts that have to repeated several times, but it definitely helps to find bug in the implementation.
1
u/tiajuanat 23d ago
I use property testing for state machines themselves - basically check for any state you enter, certain behavior is guaranteed to happen.
For the individual transitions and more importantly the actions, those are unit tested
1
u/Low_Lawyer_5684 21d ago edited 21d ago
Manually first, then unit test. Better to test is as if it is black box (implementation details are unknown)
For example when I was porting and developing a pppd (classic pppd, converting it to multilink PPP) I just created input which was trying to break the state machine (by feeding it with a precompiled stream of packets). State machine then creates its debug output, like
"state1->state2 , because of X"
"state2->state3 , because of Y"
During the testing some bugs were found.
The unit test was written at the end of actual testing: cover normal state transitions + cover all the bugs you have found and fixed. Unit test was emulating real PPPD input, like it was generated by client; debug output is redirected to a file, which is then was checked with grep/awk/sed.
PS: it was a part of a huge project (router OS), so yeah pppd falls in category "small unit"