helper test function

3,548 views
Skip to first unread message

George

unread,
Feb 1, 2012, 12:24:11 AM2/1/12
to Google C++ Testing Framework
Hi,

First of all, great product, I am using gtest in every my c++ project
and I love it.

My question is how most elegant I can implement helper test functions.
For example I have test fixtures that looks like this:

class ParserTests : public ::testing::Test
{
...

bool parse(const char* input)
{
//... something that changes mMsgs based on input
}

void checkMessage(size_t mIndex, Severity severity, ...)
{
ASSERT_LT(mIndex, mMsgs.size());
EXPECT_EQ(severity, mMsg[mIndex].severity);
}
...

std::vector<Message> mMsgs;
}

Where the body of checkMessage is relatively big and complex and I do
not want to repeat it in every my test. Then I have my tests:

TEST_F(ParserTests, whateverWrongStream)
{
ASSERT_FALSE( parse("something") );

checkMessage(0, Severity::Error, ...);
checkMessage(1, Severity::Warning, ...);
....
}

This though has serious drawback - when the test fails it points to
the line in the helper method, not to the line in the test itself.
Keep in mind that I have multiple calls from multiple tests for the
same helper method. Finding which one exactly fails is a not so
trivial as you would expect.

to eliminate this I defined a set of helper macros:
#define HF_ASSERT_LT(a, b) \
EXPECT_LT(a, b); \
if ((a) >= (b)) return false;

#define HF_EXPECT_EQ(a, b) \
EXPECT_EQ(a, b); \
if ((a) != (b)) result = false;

The fixture helper method looks like this:

bool checkMessage(size_t mIndex, Severity severity, ...)
{
bool result = true;
HF_ASSERT_LT(mIndex, mMsg.size());
HF_EXPECT_EQ(severity, mMsg[mIndex].severity);
...
return result;
}

and the test:

TEST_F(ParserTests, whateverWrongStream)
{
ASSERT_FALSE( parse(
"something") );

EXPECT_TRUE(checkMessage(0, Severity::Error, ...));
EXPECT_TRUE(checkMessage(1, Severity::Warning, ...));
}

I am curious is there better way to achieve this? I checked Value
Parameterized Tests and the other examples and they seems to me can
not be applied for exactly what I am doing. This makes me a little bit
nervous - am I the only one who uses helper methods in his tests?

Thanks you,
George






Vlad Losev

unread,
Feb 7, 2012, 8:26:44 AM2/7/12
to Google C++ Testing Framework
You can use the SCOPED_TRACE macro, but I would advice you to use helper functions to only calculate values for checking and perform checks in the body of the test. The checks can be made arbitrarily sophisticated using custom predicate assertions or ASSERT_THAT from Google Mock.
Reply all
Reply to author
Forward
0 new messages