What do you guys use to write unit tests in C? I look at some libs such as check, cmocka, gtest etc, but they all seem like way more than I need. Also, I have a hard time to separate test files and source code files (directory structure wise).
Any recommendations?

  • 4
    I don't do unit tests at all and use integration tests instead, targeting functionality independent of the implementation.

    If test and implementation are tightly coupled like in unit tests, refactoring just won't happen because that becomes too much work, and that leads to architecture rot.

    If possible (embedded), I also mock up the whole thing on the PC. The trick is a layered architecture where the source files for the lowest levels exist twice, with the PC version often just being empty stub functions.
  • 0
    For C++, I generally use GoogleTest or Catch2, unless the project is tiny (and sometimes even then). For C-only projects, for me, they've all been small enough that just hand munging something worked fine.

    Setting everything up in your build/test environment is always a bit of a chore, but you can copy-paste from a previous project and tweak as desired.

    Both of these make it easy to write simple tests (Catch2 might have the advantage), but they deal with more complex tests in different ways.
  • 3
    One thing to consider is to forego a testing library altogether.

    #include <assert.h>

    int main(void) {
    assert(some_var == 10);
    return 0;

    if the program exits 0, then your tests have passed. This is oft what I do with CTest.
  • 0
    Now I'm curious, do you write integration tests for edge cases? How much time does it take to run your entire test suite?
  • 0
    @SuspiciousBug The tests go requirement based, and they do include the limit values as far as possible (with respect e.g. to hardware tolerance). Running a full test suite can easily take some days, but writing them isn't as much effort because it's often the same tests just with different parameters.

    Before that, there are code reviews with before/after diff, and anything that even looks suspicious needs to be cleared up.

    What this requires is the ability to read code and execute it in your head, but I need that also for in-prod debugging because the prod systems aren't accessible aftersales, and all I get are pretty vague bug reports.

    Actual code bugs are rare - it's mostly issues already in the requirements, in particular with respect to unexpected physical side effects, or hardware shortcomings that need a software workaround.
  • 0
    @SuspiciousBug For private stuff, I also rely more on code review for correctness. Sometimes, I use print output to check data processing, but that's rare.

    I'm using static code analysers, and in my current side project, I have a pretty good testing infrastructure that I routinely run for days. Like ten thousands of runs and abusing my little APU for 24/7 multi-threaded number crunching.
Add Comment