Unit Testing – Adding Unit Tests to a Legacy Plain C Project

clegacyrefactoringunit testing

The title says it all. My company is reusing a legacy firmware project for a microcontroller device, written completely in plain C.

There are parts which are obviously wrong and need changing, and coming from a C#/TDD background I don't like the idea of randomly refactoring stuff with no tests to assure us that functionality remains unchanged. Also, I've seen that hard to find bugs were introduced in many occasions through slightest changes (which is something which I believe would be fixed if regression testing was used). A lot of care needs to be taken to avoid these mistakes: it's hard to track a bunch of globals around the code.

To summarize:

  • How do you add unit tests to existing tightly coupled code before refactoring?
  • What tools do you recommend? (less important, but still nice to know)

I am not directly involved in writing this code (my responsibility is an app which will interact with the device in various ways), but it would be bad if good programming principles were left behind if there was a chance they could be used.

Best Answer

Grab a copy of Working Effectively With Legacy Code by Michael Feathers. It is meant to deal with such situations. Even though it is focused more on OO languages such as C++ and Java, I believe it may still help you a lot.

Looks like part of it (or an early draft article) is even available for free here.

Related Topic