Wednesday, 11 September 2013

Checking result of EXPECT_* macros in GTest or run code when ASSERT_* failed

Checking result of EXPECT_* macros in GTest or run code when ASSERT_* failed

I have written C++ tests with GTest which basically work like this
MyData data1 = runTest(inputData);
MyData data2 = loadRegressionData();
compareMyData(data1,data2);
with
void compareMyData(MyData const& data1, MyData const& data2)
{
ASSERT_EQ(data1.count, data2.count);
//pseudo:
foreach element in data1/data2:
EXPECT_EQ(data1.items[i], data2.items[i]);
}
Now I would like to save the data1 contents to a file IFF the test fails
and I don't see an elegant solution yet.



First approach: Make compareMyData return the comparison result. This
can't work with the ASSERT_EQ which is fatal. Writing if (!EXPECT_EQ(...))
doesn't compile so the only way I found is
bool compareMyData(MyData const& data1, MyData const& data2)
{
EXPECT_EQ(data1.count, data2.count);
if (data1.count != data2.count)
return false;
//pseudo:
foreach element in data1/data2:
{
EXPECT_EQ(data1.items[i], data2.items[i]);
if (data1.items[i]!= data2.items[i])
return false;
}
}
Not very elegant :-(



Second idea: Run code when the test failed
I know I can implement ::testing::EmptyTestEventListener and get notified
if a test fails, but that doesn't give me the data I want to write to file
and it is "far away" from the place I'd like it to have. So my question
here is: Is there a way to run code at the end of a test if it failed
(e.g. catching an exception?).



To ask more general: how would you solve this?

No comments:

Post a Comment