Search code examples
c++unit-testinggoogletest

Unit testing a function with assertions


I have the following assert macro definition:

#define ASSERT_IF(expression)   \
    if (expression) {           \
        __debugbreak();         \
    }

And the following function that uses the assert macro:

std::string createFilename(std::string_view name, std::string_view extension) {
    ASSERT_IF(name.empty() || extension.empty());

    std::string result;
    result += name;
    result += '.';
    result += extension;
    return result;
}

How can I unit test such functions where input arguments are verified using assert macro? Or is there some kind of pattern that could be used to verify the input and then be able to unit test that function?


Solution

  • Quite easily actually, if you can use googletest. If you want to check that your program crashes on empty filename, simple death test does the job:

    TEST(xxxDeathTest, yyy)
    {
        ASSERT_DEATH(createFilename("", ""), "");
    }
    

    By __debugbreak I guess you are on Windows. If you could use Linux, then you could be more specific and use testing::KilledBySignal to check that your program was killed by SIGTRAP.