无法在谷歌测试中检查异常类型

Unable to check exception type in google test

本文关键字:检查 异常 类型 测试 谷歌      更新时间:2023-10-16

我无法检查我的代码在gtests中抛出的异常。下面是运行测试的测试套件的代码片段:

EXPECT_THROW({
        try{
            // Insert a tuple with more target columns than values
            rows_changed = 0;
            query = "INSERT INTO test8(num1, num3) VALUES(3);";
            txn = txn_manager.BeginTransaction();
            plan = TestingSQLUtil::GeneratePlanWithOptimizer(optimizer, query, txn);
            EXPECT_EQ(plan->GetPlanNodeType(), PlanNodeType::INSERT);
            txn_manager.CommitTransaction(txn);
            TestingSQLUtil::ExecuteSQLQueryWithOptimizer(
                optimizer, query, result, tuple_descriptor, rows_changed, error_message);
            }
        catch (CatalogException &ex){
            EXPECT_STREQ("ERROR:  INSERT has more target columns than expressions", ex.what());
            }
  }, CatalogException);

我很确定CatalogException被扔掉了。我什至尝试通过将其输出到cerr来获取抛出异常的详细信息,它显示了Exception Type: Catalog.

这不是一个重复的问题,我在SO上搜索了答案,但我没有在我的代码中使用new,这引发了错误。这是执行此操作的代码片段:

if (columns->size() < tup_size)
      throw CatalogException(
          "ERROR:  INSERT has more expressions than target columns");

最后,这是CatalogException的定义:

class CatalogException : public Exception {
  CatalogException() = delete;
 public:
  CatalogException(std::string msg) : Exception(ExceptionType::CATALOG, msg) {}
};

> EXPECT_THROW的想法是,宏捕获异常。如果您自己捕获异常,gmock 现在不会对抛出的异常进行任何操作。

我建议将语句写入EXPECT_THROW,这实际上触发了异常。其他一切都可以在之前写。

例如:

 TEST(testcase, testname) 
 {
  //arrange everything:
  //...
  //act + assert:
  EXPECT_THROW(TestingSQLUtil::ExecuteSQLQueryWithOptimizer( optimizer, query, result,
   tuple_descriptor, rows_changed, error_message)
   ,CatalogException);
}

我假设,TestingSQLUtil::ExecuteSQLQueryWithOptimizer触发抛出的异常。

加法:我试图重建您的异常层次结构。这个例子对我非常有效。测试通过,这意味着引发异常。

enum class ExceptionType
{
    CATALOG
};
class Exception {
public:
    Exception(ExceptionType type, std::string msg) {}
};
class CatalogException : public Exception {
    CatalogException() = delete;
public:
    CatalogException(std::string msg)  : Exception(ExceptionType::CATALOG, msg) {}
};
void testThrow() {
    throw CatalogException( "ERROR:  INSERT has more expressions than target columns");
}
TEST(a,b) {
    EXPECT_THROW( testThrow(), CatalogException);
}