Unit Testing Frameworks for C [duplicate]

2020-02-12 05:36发布

Possible Duplicate:
Unit Testing C Code

I've seen a few questions specific to C++, but I'm really curious about C. I'm trying to add a standard unit test framework into our build environment. My primary goals are to encourage our developers to write unit tests, and to standardize those test so others can run them. Ideally I'd like to run the unit tests as part of our nightly build.

We started some work with CUnit, which worked except that everything ran in one thread and any memory faults caused the unit tests to stop running, which was rather annoying. I also found it incredibly difficult to write the tests, but that might just be unit testing for you.

Does anybody know of good alternatives? Has anybody had any experience with the C++ Unit Testers with C-only code?

3条回答
Explosion°爆炸
2楼-- · 2020-02-12 06:18

We started some work with CUnit, which worked except that everything ran in one thread and any memory faults caused the unit tests to stop running, which was rather annoying.

There one C unit testing framework that forks and executes each test cases in a separate process so that all the tests are executed even in the presence of tests that core dump : Check

However, I'm afraid of the performance penalty all these forks bring (and to be honest, I didn't give it a try). But I won't live long with any single test core dumping : I usually fix it immediately.

One trick to prevent the unit tests to core is the assertion guard, for instance: use an assertion to prevent using a NULL pointer (example with minunit).

void test_function_returning_a_pointer(void)
{
    struct_t *theStruct = function_returning_a_pointer();
    MU_ASSERT(theStruct != NULL);

    //--- now you can use the pointer 
    MU_ASSERT(theStruct->field1 == 0);

    return MU_PASSED;
}

By the way, I'm not aware of any C++ unit test framework that won't crash in case of segmentation violation.

I also found it incredibly difficult to write the tests, but that might just be unit testing for you.

Could you elaborate on your difficulties ? Are you trying to put legacy code under tests ?

查看更多
不美不萌又怎样
3楼-- · 2020-02-12 06:22

I write embedded software using C and I decided to write my own framework. It's very simple and written for MS Visual Studio. It's easily ported to other platforms.

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

If you're targeting linux I think Check might suite your needs.

查看更多
够拽才男人
4楼-- · 2020-02-12 06:23

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

查看更多
登录 后发表回答