Is there any unit testing framework for C like JUnit and Nunit for java and .NET? Or how do we test a piece of code written in C for different scenarios?
Thanks in advance......
Is there any unit testing framework for C like JUnit and Nunit for java and .NET? Or how do we test a piece of code written in C for different scenarios?
Thanks in advance......
Glib has built-in testing framework: http://library.gnome.org/devel/glib/stable/glib-Testing.html
There is also cspec, which is a very simple and easy to use BDD framework.
If you have ever used something like rspec or mocha it will be trivial to use. It doesn't even require you to write a main function.
Here is an example:
context (example) {
describe("Hello world") {
it("true should be true") {
should_bool(true) be equal to(true);
} end
it("true shouldn't be false") {
should_bool(true) not be equal to(false);
} end
it("this test will fail because 10 is not equal to 11") {
should_int(10) be equal to(11);
} end
skip("this test will fail because \"Hello\" is not \"Bye\"") {
should_string("Hello") be equal to("Bye");
} end
} end
}
Seatest is the one I wrote for myself and open sourced. The goal is to be simple, and to have a clean syntax.
http://code.google.com/p/seatest/
a kind of basic simple test would be...
#include "seatest.h"
//
// create a test...
//
void test_hello_world()
{
char *s = "hello world!";
assert_string_equal("hello world!", s);
assert_string_contains("hello", s);
assert_string_doesnt_contain("goodbye", s);
assert_string_ends_with("!", s);
assert_string_starts_with("hell", s);
}
//
// put the test into a fixture...
//
void test_fixture_hello( void )
{
test_fixture_start();
run_test(test_hello_world);
test_fixture_end();
}
//
// put the fixture into a suite...
//
void all_tests( void )
{
test_fixture_hello();
}
//
// run the suite!
//
int main( int argc, char** argv )
{
run_tests(all_tests);
return 0;
}
I'm still new to unit testing frameworks, but I've recently tried cut, check, and cunit. This seemed to counter some others' experiences (see Unit Testing C Code for a previous question), but I found cunit the easiest to get going. This also seems a good choice for me, as cunit is supposed to align well with the other xunit frameworks and I switch languages somewhat frequently.
I was very happy with CuTest the last time I needed to unit test C. It's only one .c/.h pair, comes with a small shell script which automatically finds all the tests to build the test suite and the assertion errors aren't entirely unhelpful.
Here is an example of one of my tests:
void TestBadPaths(CuTest *tc) {
// Directory doesn't exist
char *path = (char *)"/foo/bar";
CuAssertPtrEquals(tc, NULL, searchpath(path, "sh"));
// A binary which isn't found
path = (char *)"/bin";
CuAssertPtrEquals(tc, NULL, searchpath(path, "foobar"));
}
Well, just replace the J from Java by a C from... C
Althought maybe CUT is more generic.
Finally I might be byased because I really like NetBSD, but you should also give ATF a try