单元测试模板代码

Unit testing template code

假设我有很多可以用 static_assert 测试的模板代码,例如

template <typename Help>
class SomeUtil { ... };

static_assert(std::is_same<SomeUtil<Type>::type, int>::value, "message");

是否唯一的测试方法是制作只包含此 header 的 main.cpp 并编译它? -fsyntax-only 似乎没有用。

好吧,假设你有一个像 gtest 这样的测试框架,我会尝试编写一个像

这样的测试
TEST_F(MyTestClass,CheckSomeUtilCompiles) {
    std::string codeInQuestion = R"(
    #include "MyTemplate.h"
    int main() {
        // instantiate SomeUtil with some invalid condition:
        SomeUtil<int> x;
    }
    )";
    std::ofstream testFile("testcode.cpp");
    testfile << codeInQuestion;
    testfile.close();

    EXPECT_EQ(?,system("$CPP -c $CPPFLAGS testcode.cpp -o /dev/null"));
           // ^ Something other than zero
}

利用事实 gccclang 都可以读取 stdin:

clang -c -o /dev/null -xc++ - <header.h

一步一步:

  • -c - 编译但不编译 link

  • -o /dev/null - 不产生任何输出文件

  • -xc++ - 源类型为 C++

  • - - 源作为标准输入

  • <header.h - 提供您的 header 文件作为输入

请注意,您还必须传递任何与您的项目相关的 -D-I 标志。

要修复关于 #pragma once in main file 的警告,您可以:

  • 抑制它,如果你的编译器支持-Wpragma-once-outside-header

  • Feed header 间接与 echo:

    echo '#include "header.h"' | clang -c -o /dev/null -xc++ -

不要忘记尾随 -