Even C Developpers Have Their xUnit

Even C Developpers Have Their xUnit

/ Olivier Dugas

While coaching a team on how to program in a TDD fashion in C, I stumbled across this wonderful testing and mocking framework.

I often have to develop softwares in C++, so I was getting used to write tests using GoogleTest and GoogleMock. When I had to write code in C, it remained the way to go, thanks to Mike Long's blog.

But things have changed since I've found Cgreen.

I cannot express myself better than Cgreen's guide made by Baker, Nilsson and Freitas. There, you'll find how to install Cgreen and how to get started with it. They show how to build and use test suites, how to mock C functions, and how to write assertion in BDD (Behavior-Driven Development) fashion. They take you on a ride to learn all the features of the framework while coding a kata that you can redo while you read.

Here's a glimpse of how the framework is used. Enjoy!

#include <cgreen/cgreen.h>
#include <cgreen/mocks.h>


int functionToMock(int x, int y)
    return mock(x, y);

{ /*Do something*/ }

{ /*Do something*/ }

Ensure(ExampleSuite, myFirstTest_shouldExpectSomethingFromMock)
    expect(functionToMock, when(x, is_greater_than(0)), will_return(42));

    int result = functionIWantToTest(&functionToMock);

    assert_that(result, is_equal_to(0));

int main() {
    TestSuite *suite = create_test_suite();
    add_test_with_context(suite, ExampleSuite, myFirstTest_shouldExpectSomethingFromMock);
    return run_test_suite(suite, create_text_reporter());