ASSERT_THROW认为我的异常属于另一种类型

ASSERT_THROW thinks my exception is of a different type

本文关键字:异常 属于 另一种 类型 我的 THROW ASSERT      更新时间:2023-10-16

在Google测试中,当我运行以下测试时:

void ThrowInvalidArgument()
{
   throw new std::invalid_argument("I am thrown an invalid_argument");
}
TEST(ExpectExceptions, Negative)
{
  ASSERT_THROW(ThrowInvalidArgument(), std::invalid_argument);
}

我得到以下失败:

error: Expected: ThrowInvalidArgument() throws an exception
                 of type std::invalid_argument.
       Actual: it throws a different type.
[  FAILED  ] ExpectExceptions.Negative (1 ms)

我做错了什么?

您正在抛出std::invalid_argument*类型的实例,即指针

投掷一个物体:

void ThrowInvalidArgument()
{
     throw std::invalid_argument("I am thrown an invalid_argument");
     //   ^ (no new)
}

扩展Pjoter的有效答案:异常总是应该从普通的临时实例中抛出,并作为常量引用捕获:

void ThrowInvalidArgument() {
    throw std::invalid_argument("I am thrown an invalid_argument");
}
void Elsewhere {
    try {
    }
    catch(const std::invalid_argument& invalidArgEx) {
    }
}