gtest - 使用 EXPECT_EQ 报告循环的索引变量

gtest - Report index variable for loop with EXPECT_EQ

我正在使用 gtest,但我是 gtest 的新手。我想比较两个 std::vectors 复杂数据结构中的值。我想做这样的事情:

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)));
}

这很棒,因为对于不匹配,它会报告比较的值,例如5 != 7,但它不报告索引变量"x"。有什么方法可以在检测到不匹配时轻松输出索引变量?

来自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.

所以如果你想输出你的指数是什么期望相等,你会做这样的事情:

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;
可以使用

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

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

当检查不止一项时特别有用:

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