Curious
Curious

Reputation: 21560

Unit testing template code

Imagine that I have a lot of template code that I can test with static_asserts, so for example

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

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

Is the only way to test this by making a main.cpp that just includes this header and compiling it? -fsyntax-only did not seem to work.

Upvotes: 2

Views: 1092

Answers (2)

user2512323
user2512323

Reputation:

Using the fact gcc and clang both can read stdin:

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

Step by step:

  • -c - compile but not link

  • -o /dev/null - do not produce any output files

  • -xc++ - source type would be C++

  • - - source given as stdin

  • <header.h - supply your header file as input

Note that you must also pass any relevant to your project -D or -I flags.

To fix warning about #pragma once in main file, you can either:

  • Suppress it, if your compiler supports -Wpragma-once-outside-header

  • Feed header indirectly with echo:

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

Do not forget the trailing -.

Upvotes: 1

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Well, lest's assume you have a testing framework like gtest, I'd try to write a test like

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
}

Upvotes: 2

Related Questions