Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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(xxx, 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading