jeudi 17 juin 2021

Uncoupling C code for easier unit testing

I have an embedded project written in C code. It is divided into "components" which are responsible for smaller groups of tasks. For example, there is:

  • I2C component, which reads data from sensors connected to I2C bus
  • msgpack component, which gets sensors data and serializes them to msgpack format
  • MQTT component, which gets memory buffer and sends it to the broker
  • Settings component, with all the configuration for the project

Those four components are highly coupled together, because:

  • I2C depends on Settings for PIN configuration.
  • msgpack depends on I2C for "structured" data it takes as an input.
  • MQTT component depends on Settings for URL, PORT and other settings.

Unit testing those components seems too hard due to the coupling. Instead of writing unittest, I end up with either:

  • writing a lot of mock code, just to "decouple" required components
  • including required components

In the first case, any change in "coupled" components means, that I have to rewrite most of the tests.

In the seconds, it is not an unit test anymore, more like integration test.

I suppose, this all is cause by my bad code organization, but to be honest, I don't see any way how to organize/rewrite it to make it better.

I would like to know, if there are some patterns or principles to follow to decouple parts of the code, which needs to pass data from one to another.

I don't want to end up with untestable spaghetti code.

Thank you.

Aucun commentaire:

Enregistrer un commentaire