Google Test 可以测试 C 代码吗?

所以我开始喜欢和享受在我参与的一个 C + + 项目中使用 Google Test。我只是提出了一个新的项目,将直 C (库) ,到目前为止看不到任何理由为什么不继续使用谷歌测试,即使它是一个 C + + 框架。使用 C + + 编译器不是问题。

有没有什么特别的原因让我不能使用 Google Test 来测试直接的 C 代码?

谢谢。

57476 次浏览

I could not name one. I guess there will be some things which you don't have in "normal" C. E.g I think the TestCase are derived from a certain class. But within the test you can test whatever you like and so why not C?

As all Google's C++ code, Google Test does not use exceptions, so exception safety flow won't be an issue. As long as your headers are C++-compatible (not using C++ keywords, export symbols with correct linkage), it should be fine.

It is pretty common to test C code using a C++ testing frameworks, even the leading book on the subject follows this approach. I have used googletest extensively in the past to unit test C code and can recommend it.

I have written a blog post about it that might be useful: http://meekrosoft.wordpress.com/2009/11/09/unit-testing-c-code-with-the-googletest-framework/

Jason, be aware of that!!! :D

As Meekrosoft said, yes, it is possible. I also used his website when I tried to do that. It works, but there is one big problem:

GTest is objected oriented tool and C language isn't!

In example, in GTest you have a lot of functions (80% of whole API) that request object as parameter, for example:

EXPECT_CALL(turtle, PenDown())              // turtle is object(class) and PenDown() is method of that object
.Times(AtLeast(1));

from GTest website gmock_for_dummies.md so you will use only macros like expect_equal, expect_bigger_than and so on...

I would like to suggest you tool CMocka (or some other C unit testing tools). It is also from google (modified by group of non-google developers) and it is created directly for C language. I use this one when I want to test C-type source code.

I hope this helps.. :-) Have a nice day.. :-)

I just thought I'd add another point: since gtest is C++, you'll be parsing your C headers under test as C++. This means the tests don't guarantee that the headers are consumable from C. I recently ran into this with a C library I'm building.