Void’s Vault

Knowledge source for efficiency.

Even C Developpers Have Their xUnit

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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <cgreen/cgreen.h>
#include <cgreen/mocks.h>

Describe(ExampleSuite)

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

BeforeEach(ExampleSuite)
{ /*Do something*/ }

AfterEach(ExampleSuite)
{ /*Do something*/ }

Ensure(ExampleSuite, myFirstTest_shouldExpectSomethingFromMock)
{
  cgreen_mocks_are(loose_mocks);
  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());
}