GTest 等库如何使用单个宏 G_TEST(...)
来定义函数并将其注册为测试函数?我正在寻找一种方法来为我的 C99 项目做同样的事情。
示例
#include <stdio.h>
#include "my_test_header_that_doesnt_exist.h"
TEST_MACRO(mytest)
{
printf("Hello, world\n");
return 0;
}
TEST_MACRO(mytest2)
{
printf("Hello, world 2\n");
return 2;
}
int main(int argc, char** argv)
{
RUN_TESTS();
return 0;
}
无法弄清楚如何注册测试,以便从 RUN_TESTS()
得知它们
最佳答案
通过将 -E
选项传递给 g++
,您可以在预处理后检查代码。使用 GTest 库的示例代码:
#include <gtest/gtest.h>
TEST(testcase, mytest) {
// Code
}
int main() {
return RUN_ALL_TESTS();
}
并编译它:
g++ -E -Igtest_include_path example.cpp -oexample_preprocessed.cpp
TEST 宏扩展为:
class testcase_mytest_Test : public ::testing::Test {
public:
testcase_mytest_Test() {}
private:
virtual void TestBody();
static ::testing::TestInfo* const test_info_ __attribute__ ((unused));
testcase_mytest_Test(testcase_mytest_Test const &);
void operator=(testcase_mytest_Test const &);
};
::testing::TestInfo* const testcase_mytest_Test ::test_info_ = ::testing::internal::MakeAndRegisterTestInfo( "testcase", "mytest", __null, __null, ::testing::internal::CodeLocation("cpp_test.c", 3), (::testing::internal::GetTestTypeId()), ::testing::Test::SetUpTestCase, ::testing::Test::TearDownTestCase, new ::testing::internal::TestFactoryImpl< testcase_mytest_Test>);
void testcase_mytest_Test::TestBody() {
// Code
}
并且 RUN_ALL_TESTS() 不是宏:
inline int RUN_ALL_TESTS() {
return ::testing::UnitTest::GetInstance()->Run();
}
所以它实际上是一个复杂的预处理器宏链,它从测试用例中组成一个类,并执行各种操作将其链接到运行它的机器。
显然,您无法在 C99 项目中这样做,因为 GTest 是一个 C++ 库,并且它严重依赖 C++ 功能来完成这项工作。
如果您想了解它的完整工作原理,您应该查看其存储库中的 GTest 代码:https://github.com/google/googletest
关于C、宏如何注册一个单元测试来执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38673694/