Philipp
Philipp

Reputation: 11814

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?

Upvotes: 4

Views: 4785

Answers (2)

jstar
jstar

Reputation: 877

The way around:

bool HasError = false;
FAIL() << (HasError = true);
if (HasError){
 // do something
}

Instead of FAIL() could be ASSERT_.. EXPECT_... and so on. (in output you'll see "true" it's a fee for shortcut).

Upvotes: 0

bchurchill
bchurchill

Reputation: 1420

On the advanced guide that VladLosev linked, it says,

Similarly, HasNonfatalFailure() returns true if the current test has at least one non-fatal failure, and HasFailure() returns true if the current test has at least one failure of either kind.

So calling HasNonfatalFailure might be what you want. (I'm pretty late, but had the same question.)

Upvotes: 2

Related Questions