952

I worked on an embedded system this summer written in straight C. It was an existing project that the company I work for had taken over. I have become quite accustomed to writing unit tests in Java using JUnit but was at a loss as to the best way to write unit tests for existing code (which needed refactoring) as well as new code added to the system.

Are there any projects out there that make unit testing plain C code as easy as unit testing Java code with JUnit? Any insight that would apply specifically to embedded development (cross-compiling to arm-linux platform) would be greatly appreciated.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Paul Osborne
  • 5,024
  • 6
  • 24
  • 20

31 Answers31

556

One unit testing framework in C is Check; a list of unit testing frameworks in C can be found here and is reproduced below. Depending on how many standard library functions your runtime has, you may or not be able to use one of those.

AceUnit

AceUnit (Advanced C and Embedded Unit) bills itself as a comfortable C code unit test framework. It tries to mimick JUnit 4.x and includes reflection-like capabilities. AceUnit can be used in resource constraint environments, e.g. embedded software development, and importantly it runs fine in environments where you cannot include a single standard header file and cannot invoke a single standard C function from the ANSI / ISO C libraries. It also has a Windows port. It does not use forks to trap signals, although the authors have expressed interest in adding such a feature. See the AceUnit homepage.

GNU Autounit

Much along the same lines as Check, including forking to run unit tests in a separate address space (in fact, the original author of Check borrowed the idea from GNU Autounit). GNU Autounit uses GLib extensively, which means that linking and such need special options, but this may not be a big problem to you, especially if you are already using GTK or GLib. See the GNU Autounit homepage.

cUnit

Also uses GLib, but does not fork to protect the address space of unit tests.

CUnit

Standard C, with plans for a Win32 GUI implementation. Does not currently fork or otherwise protect the address space of unit tests. In early development. See the CUnit homepage.

CuTest

A simple framework with just one .c and one .h file that you drop into your source tree. See the CuTest homepage.

CppUnit

The premier unit testing framework for C++; you can also use it to test C code. It is stable, actively developed, and has a GUI interface. The primary reasons not to use CppUnit for C are first that it is quite big, and second you have to write your tests in C++, which means you need a C++ compiler. If these don’t sound like concerns, it is definitely worth considering, along with other C++ unit testing frameworks. See the CppUnit homepage.

embUnit

embUnit (Embedded Unit) is another unit test framework for embedded systems. This one appears to be superseded by AceUnit. Embedded Unit homepage.

MinUnit

A minimal set of macros and that’s it! The point is to show how easy it is to unit test your code. See the MinUnit homepage.

CUnit for Mr. Ando

A CUnit implementation that is fairly new, and apparently still in early development. See the CUnit for Mr. Ando homepage.

This list was last updated in March 2008.

More frameworks:

CMocka

CMocka is a test framework for C with support for mock objects. It's easy to use and setup.

See the CMocka homepage.

Criterion

Criterion is a cross-platform C unit testing framework supporting automatic test registration, parameterized tests, theories, and that can output to multiple formats, including TAP and JUnit XML. Each test is run in its own process, so signals and crashes can be reported or tested if needed.

See the Criterion homepage for more information.

HWUT

HWUT is a general Unit Test tool with great support for C. It can help to create Makefiles, generate massive test cases coded in minimal 'iteration tables', walk along state machines, generate C-stubs and more. The general approach is pretty unique: Verdicts are based on 'good stdout/bad stdout'. The comparison function, though, is flexible. Thus, any type of script may be used for checking. It may be applied to any language that can produce standard output.

See the HWUT homepage.

CGreen

A modern, portable, cross-language unit testing and mocking framework for C and C++. It offers an optional BDD notation, a mocking library, the ability to run it in a single process (to make debugging easier). A test runner which discover automatically the test functions is available. But you can create your own programmatically.

All those features (and more) are explained in the CGreen manual.

Wikipedia gives a detailed list of C unit testing frameworks under List of unit testing frameworks: C

Community
  • 1
  • 1
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • Initially, Check looks very solid. I will have to see how it holds up under the fire of real use... but it definitely looks like it may fit the bill. – Paul Osborne Sep 16 '08 at 01:30
  • 8
    We use check for unit testing code on our embedded systems. For the most part check was a good choice but now we are working on systems running on uClinux and since check requires fork it doesn't work on those systems. :/ – David Holm Oct 15 '08 at 12:43
  • It seems like CUnit has more activity. The version of Check that came in the Ubuntu repo for 12.04 is buggy. – labyrinth Apr 15 '13 at 01:44
  • 1
    @labyrinth The one in Ubuntu dates from 2002. The most current version is from this year (2014 as of this comment). I had to compile it from source. – Barry Brown Feb 25 '14 at 23:52
  • 4
    HWUT does generate remote-controllable stubs which comes pretty handy if you want to write tests for modules that interact with hardward drivers. Those drivers are, in most cases not present on a PC. [HWUT Documentation](http://hwut.sourceforge.net/html/stubs/intro.html) – Frank-Rene Schäfer Sep 22 '15 at 13:59
  • I use HWUT at work and it works very well – Eltges Oct 21 '15 at 13:04
  • 1
    According to [Check's Github Page](https://github.com/libcheck/check/releases), the latest version is `0.11.0` released on **Dec 17, 2016**. – Mandeep Sandhu Feb 09 '17 at 01:32
  • @DamienFlament: Ugh — IMNSHO, moving all the URLs to the bottom instead of leaving them beside the referring link citation makes maintenance harder, not easier. I'm sorely tempted to rollback your change. – Jonathan Leffler Jan 15 '19 at 00:15
  • Hmm how about adding CppUTest ? The tests can be coded in C or C++ and provide ability to write mocks. No automatic mock generation i think, but they supply scripts to aid in coding the mocks. – Razzle Dec 23 '20 at 17:48
187

Personally I like the Google Test framework.

The real difficulty in testing C code is breaking the dependencies on external modules so you can isolate code in units. This can be especially problematic when you are trying to get tests around legacy code. In this case I often find myself using the linker to use stubs functions in tests.

This is what people are referring to when they talk about "seams". In C your only option really is to use the pre-processor or the linker to mock out your dependencies.

A typical test suite in one of my C projects might look like this:

#include "myimplementationfile.c"
#include <gtest/gtest.h>

// Mock out external dependency on mylogger.o
void Logger_log(...){}

TEST(FactorialTest, Zero) {
    EXPECT_EQ(1, Factorial(0));
}

Note that you are actually including the C file and not the header file. This gives the advantage of access to all the static data members. Here I mock out my logger (which might be in logger.o and give an empty implementation. This means that the test file compiles and links independently from the rest of the code base and executes in isolation.

As for cross-compiling the code, for this to work you need good facilities on the target. I have done this with googletest cross compiled to Linux on a PowerPC architecture. This makes sense because there you have a full shell and os to gather your results. For less rich environments (which I classify as anything without a full OS) you should just build and run on the host. You should do this anyway so you can run the tests automatically as part of the build.

I find testing C++ code is generally much easier due to the fact that OO code is in general much less coupled than procedural (of course this depends a lot on coding style). Also in C++ you can use tricks like dependency injection and method overriding to get seams into code that is otherwise encapsulated.

Michael Feathers has an excellent book about testing legacy code. In one chapter he covers techniques for dealing with non-OO code which I highly recommend.

Edit: I've written a blog post about unit testing procedural code, with source available on GitHub.

Edit: There is a new book coming out from the Pragmatic Programmers that specifically addresses unit testing C code which I highly recommend.

mikelong
  • 3,694
  • 2
  • 35
  • 40
  • 19
    Don't buy the prag. prog book. It doesn't contain any insights that are not in the answers to this question. – Phil Dec 11 '12 at 13:31
  • 5
    I know C and C++ has a lot of overlap, but it doesn't strike me as a good idea to use a C++ testing library when you're producing code that will be ultimately compiled in a C compiler. – Rafael Almeida Dec 01 '14 at 18:13
  • 3
    @RafaelAlmeida in essence I agree, what I show here is a preprocessor seam without wrapping the C include in an extern C. Regardless of that I found C++ quite handy as a test description language in practice. I have also written a C based framework for testing so I'm not dogmatic about this :-) https://github.com/meekrosoft/fff – mikelong Dec 02 '14 at 20:46
  • @Phil I disagree. I found the book to be very valuable, especially for someone who is not real strong in C. – CHendrix Mar 14 '16 at 12:21
  • I'm using the Fake Function Framework for mocking HAL functions, as stated above. It works very well with gTest. https://github.com/meekrosoft/fff – Leonardo Jan 24 '20 at 17:55
144

Minunit is an incredibly simple unit testing framework. I'm using it to unit test c microcontroller code for avr.

tanascius
  • 53,078
  • 22
  • 114
  • 136
Matteo Caprari
  • 2,869
  • 4
  • 27
  • 35
  • 6
    I have no experience in doing embedded systems so I cannot comment on that, but for small C programs (schoolwork, scripts) this looks perfect. Great link. – AndrewKS May 31 '11 at 23:52
  • 3
    @toasted_flakes I've made this into a github gist: https://gist.github.com/sam159/0849461161e86249f849 – Sam Aug 27 '14 at 21:30
  • This is pretty close to what I came up with before I started searching here! I would like to automate the testing so that TEST(funcname, body) creates the function and stores a pointer to the function, but it looks like I'll need to to some external processing. – Ben Kushigian Jan 17 '17 at 20:56
50

I say almost the same as ratkok but if you have a embedded twist to the unit tests then...

Unity - Highly recommended framework for unit testing C code.

#include <unity.h>

void test_true_should_be_true(void)
{
    TEST_ASSERT_TRUE(true);
}

int main(void)
{
    UNITY_BEGIN();
    RUN_TEST(test_true_should_be_true);
    return UNITY_END();
}

The examples in the book that is mentioned in this thread TDD for embedded C are written using Unity (and CppUTest).

Johan
  • 20,067
  • 28
  • 92
  • 110
43

I'm currently using the CuTest unit test framework:

http://cutest.sourceforge.net/

It's ideal for embedded systems as it's very lightweight and simple. I had no problems getting it to work on the target platform as well as on the desktop. In addition to writing the unit tests, all that's required is:

  • a header file included wherever you're calling the CuTest routines
  • a single additional 'C' file to be compiled/linked into the image
  • some simple code added to to main to set up and call the unit tests - I just have this in a special main() function that gets compiled if UNITTEST is defined during the build.

The system needs to support a heap and some stdio functionality (which not all embedded systems have). But the code is simple enough that you could probably work in alternatives to those requirements if your platform doesn't have them.

With some judicious use of extern "C"{} blocks it also supports testing C++ just fine.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • 1
    I'll second the vote for CuTest. I've been using it for developing homebrew on the Nintendo DS and haven't had any difficulty getting it set up or using it. – Theran Feb 11 '09 at 17:55
  • I'll third this. I downloaded it when it was version 1.4 and modified it to dump to XML. It looks like there's a version 1.5 that I'll have to download and look at. – Taylor Price Feb 23 '11 at 20:29
  • 2
    CuTest has worked well for me to test code running on a QNX system. – Jace Browning Jul 28 '11 at 19:38
  • It claims to work like JUnit, but I seem to miss `Before` and `After` calls. All in all, it's cute. – Dragas Mar 20 '19 at 14:52
  • CuTest works very well! With its already supplied make-tests.sh script you don't have to write your main() and add in all your tests...just add in your function to test and off you go! Using it for embedded systems and already catching legacy weaknesses. Together with fff.h it works a charm for mocking functions and more. – Joel Ravazzolo Jun 21 '22 at 09:41
37

You also might want to take a look at libtap, a C testing framework which outputs the Test Anything Protocol (TAP) and thus integrates well with a variety of tools coming out for this technology. It's mostly used in the dynamic language world, but it's easy to use and becoming very popular.

An example:

#include <tap.h>

int main () {
    plan(5);

    ok(3 == 3);
    is("fnord", "eek", "two different strings not that way?");
    ok(3 <= 8732, "%d <= %d", 3, 8732);
    like("fnord", "f(yes|no)r*[a-f]$");
    cmp_ok(3, ">=", 10);

    done_testing();
}
Lucas Sampaio
  • 1,568
  • 2
  • 18
  • 36
Ovid
  • 11,580
  • 9
  • 46
  • 76
28

There is an elegant unit testing framework for C with support for mock objects called cmocka. It only requires the standard C library, works on a range of computing platforms (including embedded) and with different compilers.

It also has support for different message output formats like Subunit, Test Anything Protocol and jUnit XML reports.

cmocka has been created to also work on embedded platforms and also has Windows support.

A simple test looks like this:

#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>

/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) {
    (void) state; /* unused */
}

int main(void) {
    const struct CMUnitTest tests[] = {
        cmocka_unit_test(null_test_success),
    };
    return cmocka_run_group_tests(tests, NULL, NULL);
}

The API is fully documented and several examples are part of the source code.

To get started with cmocka you should read the article on LWN.net: Unit testing with mock objects in C

cmocka 1.0 has been released February 2015.

asn
  • 798
  • 9
  • 17
21

I didn't get far testing a legacy C application before I started looking for a way to mock functions. I needed mocks badly to isolate the C file I want to test from others. I gave cmock a try and I think I will adopt it.

Cmock scans header files and generates mock functions based on prototypes it finds. Mocks will allow you to test a C file in perfect isolation. All you will have to do is to link your test file with mocks instead of your real object files.

Another advantage of cmock is that it will validate parameters passed to mocked functions, and it will let you specify what return value the mocks should provide. This is very useful to test different flows of execution in your functions.

Tests consist of the typical testA(), testB() functions in which you build expectations, call functions to test and check asserts.

The last step is to generate a runner for your tests with unity. Cmock is tied to the unity test framework. Unity is as easy to learn as any other unit test framework.

Well worth a try and quite easy to grasp:

http://sourceforge.net/apps/trac/cmock/wiki

Update 1

Another framework I am investigating is Cmockery.

http://code.google.com/p/cmockery/

It is a pure C framework supporting unit testing and mocking. It has no dependency on ruby (contrary to Cmock) and it has very little dependency on external libs.

It requires a bit more manual work to setup mocks because it does no code generation. That does not represent a lot of work for an existing project since prototypes won't change much: once you have your mocks, you won't need to change them for a while (this is my case). Extra typing provides complete control of mocks. If there is something you don't like, you simply change your mock.

No need of a special test runner. You only need need to create an array of tests and pass it to a run_tests function. A bit more manual work here too but I definitely like the idea of a self-contained autonomous framework.

Plus it contains some nifty C tricks I didn't know.

Overall Cmockery needs a bit more understanding of mocks to get started. Examples should help you overcome this. It looks like it can do the job with simpler mechanics.

Philippe A.
  • 2,885
  • 2
  • 28
  • 37
19

We wrote CHEAT (hosted on GitHub) for easy usability and portability.

It has no dependencies and requires no installation or configuration. Only a header file and a test case is needed.

#include <cheat.h>

CHEAT_TEST(mathematics_still_work,
    cheat_assert(2 + 2 == 4);
    cheat_assert_not(2 + 2 == 5);
)

Tests compile into an executable that takes care of running the tests and reporting their outcomes.

$ gcc -I . tests.c
$ ./a.out
..
---
2 successful of 2 run
SUCCESS

It has pretty colors too.

Tuplanolla
  • 31
  • 1
  • 2
  • 9
  • @Tuplanolla It seems the link http://users.jyu.fi/~sapekiis/cheat/ does not work anymore. But anyway github provides enough info for me to start using CHEAT. Thank you very much for your efforts:) – dehasi Dec 19 '20 at 22:15
16

As a C newbie, I found the slides called Test driven development in C very helpful. Basically, it uses the standard assert() together with && to deliver a message, without any external dependencies. If someone is used to a full stack testing framework, this probably won't do :)

chelmertz
  • 20,399
  • 5
  • 40
  • 46
  • This is the simplest TDD approach I've seen for C, that you can follow with just `assert` without any additional libraries or framework. I think if you're just a newbie, this could be a starting point. – kabirbaidhya Jul 21 '19 at 14:13
13

There is CUnit

And Embedded Unit is unit testing framework for Embedded C System. Its design was copied from JUnit and CUnit and more, and then adapted somewhat for Embedded C System. Embedded Unit does not require std C libs. All objects are allocated to const area.

And Tessy automates the unit testing of embedded software.

prakash
  • 58,901
  • 25
  • 93
  • 115
12

Michael Feather's book "Working Effectively with Legacy Code" presents a lot of techniques specific to unit testing during C development.

There are techniques related to dependency injection that are specific to C which I haven't seen anywhere else.

Anuj Gupta
  • 10,056
  • 3
  • 28
  • 32
Frank Schwieterman
  • 24,142
  • 15
  • 92
  • 130
12

I don't use a framework, I just use autotools "check" target support. Implement a "main" and use assert(s).

My test dir Makefile.am(s) look like:

check_PROGRAMS = test_oe_amqp

test_oe_amqp_SOURCES = test_oe_amqp.c
test_oe_amqp_LDADD = -L$(top_builddir)/components/common -loecommon
test_oe_amqp_CFLAGS = -I$(top_srcdir)/components/common -static

TESTS = test_oe_amqp
navicore
  • 1,979
  • 4
  • 34
  • 50
  • 3
    We are not using autotools (though it would be nice to move over at some point). Historically, I have used the main method for testing purposes and it is not a bad solution. – Paul Osborne Sep 16 '08 at 14:23
7

CppUTest - Highly recommended framework for unit testing C code.

The examples in the book that is mentioned in this thread TDD for embedded C are written using CppUTest.

ratkok
  • 739
  • 9
  • 15
6

I use CxxTest for an embedded c/c++ environment (primarily C++).

I prefer CxxTest because it has a perl/python script to build the test runner. After a small slope to get it setup (smaller still since you don't have to write the test runner), it's pretty easy to use (includes samples and useful documentation). The most work was setting up the 'hardware' the code accesses so I could unit/module test effectively. After that it's easy to add new unit test cases.

As mentioned previously it is a C/C++ unit test framework. So you will need a C++ compiler.

CxxTest User Guide CxxTest Wiki

Rob Kam
  • 10,063
  • 14
  • 55
  • 65
Zing-
  • 2,087
  • 2
  • 13
  • 12
  • The compiler you need may be c++ but the code you are testing can still be C. CxxTest is a very easy framework to use – David Sykes Sep 16 '08 at 06:44
5

other than my obvious bias

http://code.google.com/p/seatest/

is a nice simple way to unit test C code. mimics xUnit

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
5

After reading Minunit I thought a better way was base the test in assert macro which I use a lot like defensive program technique. So I used the same idea of Minunit mixed with standard assert. You can see my framework (a good name could be NoMinunit) in k0ga's blog

5

Google has excellent testing framework. https://github.com/google/googletest/blob/master/googletest/docs/primer.md

And yes, as far as I see it will work with plain C, i.e. doesn't require C++ features (may require C++ compiler, not sure).

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Paweł Hajdan
  • 18,074
  • 9
  • 49
  • 65
  • Will google's framework work with pure C? A quick glance at the page suggests it's a C++ framework. – Dana Sep 15 '08 at 19:21
  • 5
    Google Test is excellent, but it's very much a C++ framework. It is pretty portable and can be used to test C if you had to. – Josh Kelley Sep 11 '09 at 18:53
  • Unfortunately, it is not always the case the GTest allows the C code to work. For example, one won't be able to compile the code of a gtest test which includes a C header which uses atomic integers, regardless of what magic with #ifdef and other things one might want to perform in order to make it work. So, it works with C code, but it is not **always** the case that it will compile and work. – VP. Jan 23 '23 at 10:56
4

cmockery at http://code.google.com/p/cmockery/

Landon Kuhn
  • 76,451
  • 45
  • 104
  • 130
  • You should take a look at http://cmocka.org/ which is the successor of cmockery. – asn Jul 31 '13 at 07:51
4

Cmockery is a recently launched project that consists on a very simple to use C library for writing unit tests.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • You should take a look at http://cmocka.org/ which is the successor of Cmockery. – asn Jul 31 '13 at 07:50
3

First, look here: http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C

My company has a C library our customers use. We use CxxTest (a C++ unit test library) to test the code. CppUnit will also work. If you're stuck in C, I'd recommend RCUNIT (but CUnit is good too).

Kevin
  • 25,207
  • 17
  • 54
  • 57
2

I used RCUNIT to do some unit testing for embedded code on PC before testing on the target. Good hardware interface abstraction is important else endianness and memory mapped registers are going to kill you.

Gerhard
  • 6,850
  • 8
  • 51
  • 81
2

try lcut! - http://code.google.com/p/lcut

Tony Bai
  • 151
  • 2
  • 6
  • 3
    Some documentation would be helpful. Project background and goals, a features list, advantages over existing alternatives, etc would be helpful for people who are checking it out for the first time. – Craig McQueen Oct 10 '10 at 03:42
2

API Sanity Checker — test framework for C/C++ libraries:

An automatic generator of basic unit tests for a shared C/C++ library. It is able to generate reasonable (in most, but unfortunately not all, cases) input data for parameters and compose simple ("sanity" or "shallow"-quality) test cases for every function in the API through the analysis of declarations in header files.

The quality of generated tests allows to check absence of critical errors in simple use cases. The tool is able to build and execute generated tests and detect crashes (segfaults), aborts, all kinds of emitted signals, non-zero program return code and program hanging.

Examples:

Community
  • 1
  • 1
linuxbuild
  • 15,843
  • 6
  • 60
  • 87
2

If you are familiar with JUnit then I recommend CppUnit. http://cppunit.sourceforge.net/cppunit-wiki

That is assuming you have c++ compiler to do the unit tests. if not then I have to agree with Adam Rosenfield that check is what you want.

Kwondri
  • 575
  • 3
  • 4
  • 6
    The question is about C, not C++ – 1800 INFORMATION Sep 15 '08 at 19:40
  • 3
    No, but C++ can interface to C libraries. So it may in fact be perfectly fine to test C libraries using a C++ unit test framework. (My company does that very thing by the way and it's so much easier than using C unit test frameworks.) – Kevin Sep 15 '08 at 20:40
  • I do the same thing. We have a utilities library written in C that we use underneath our C++ code and scripting languages. We use CppUnit for the tests and it's working out pretty well since we can use the same framework for both C and C++. – Jyaan Oct 12 '10 at 03:06
1

I'm surprised that no one mentioned Cutter (http://cutter.sourceforge.net/) You can test C and C++, it seamlessly integrates with autotools and has a really nice tutorial available.

Kris
  • 5,714
  • 2
  • 27
  • 47
1

LibU (http://koanlogic.com/libu) has an unit test module that allows explicit test suite/case dependencies, test isolation, parallel execution and a customizable report formatter (default formats are xml and txt).

The library is BSD licensed and contains many other useful modules - networking, debugging, commonly used data structures, configuration, etc. - should you need them in your projects ...

bongo
  • 1
  • 1
1

One technique to use is to develop the unit test code with a C++ xUnit framework (and C++ compiler), while maintaining the source for the target system as C modules.

Make sure you regularly compile your C source under your cross-compiler, automatically with your unit tests if possible.

quamrana
  • 37,849
  • 12
  • 53
  • 71
0

In case you are targeting Win32 platforms or NT kernel mode, you should have a look at cfix.

Johannes Passing
  • 2,715
  • 16
  • 13
0

I just wrote Libcut out of frustration with existing C unit testing libraries. It has automatic type stringing of primitives (no need for test_eq_int, test_eq_long, test_eq_short, etc...; only two different sets for primitives and strings) and consists of one header file. Here's a short example:

#include <libcut.h>

LIBCUT_TEST(test_abc) {
    LIBCUT_TEST_EQ(1, 1);
    LIBCUT_TEST_NE(1, 0);
    LIBCUT_TEST_STREQ("abc", "abc");
    LIBCUT_TEST_STRNE("abc", "def");
}

LIBCUT_MAIN(test_abc);

It works only with C11, though.

kirbyfan64sos
  • 10,377
  • 6
  • 54
  • 75
0

If you're still on the hunt for test frameworks, CUnitWin32 is one for the Win32/NT platform.

This solves one fundamental problem that I faced with other testing frameworks. Namely global/static variables are in a deterministic state because each test is executed as a separate process.

Dushara
  • 616
  • 1
  • 5
  • 25