Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gtest - Report index variable for loop with EXPECT_EQ

I am using gtest but I am new to gtest. I would like to do compares of values within two std::vectors of complex data structures. I want to do something like this:

ASSERT_EQ(a.size(), b.size());

for (int x = 0; x < a.size(); x++) {
  EXPECT_EQ(
    sqrt(pow(a.real[x], 2) + pow(a.imag[x], 2)),
    sqrt(pow(b.real[x], 2) + pow(b.imag[x], 2)));
}

This is great in that for mismatches it reports the values that were compared, e.g. 5 != 7, but it does not report the index variable "x". Is there some way I can easily output the index variable when mismatch is detected?

like image 971
TallBrianL Avatar asked Jun 13 '18 18:06

TallBrianL


2 Answers

From https://github.com/google/googletest/blob/main/docs/primer.md:

To provide a custom failure message, simply stream it into the macro using the << operator, or a sequence of such operators.

So if you wanted to output what your index is for the expect equal, you would do something like:

EXPECT_EQ(
  sqrt(pow(a.real[x], 2) + pow(a.imag[x], 2)),
  sqrt(pow(b.real[x], 2) + pow(b.imag[x], 2))) << "x is : " << x << std::endl;
like image 55
mkamerath Avatar answered Oct 19 '22 01:10

mkamerath


SCOPED_TRACE (https://github.com/google/googletest/blob/main/docs/advanced.md#adding-traces-to-assertions) can be used, like:

for (int x = 0; x < a.size(); x++) {
  SCOPED_TRACE("x = " + std::to_string(x));
  EXPECT_EQ(
  ...

It's especially useful when there are more than one check:

for (int x = 0; x < a.size(); x++) {
  SCOPED_TRACE("x = " + std::to_string(x));
  EXPECT_EQ(...
  EXPECT_EQ(...
like image 29
user_with_zhban_piva Avatar answered Oct 19 '22 03:10

user_with_zhban_piva