You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GTest验证特定抛出异常时遇类型不匹配问题求助

问题描述

我是GTest框架的新手,希望在测试中实现异常处理。我实现了一个简单的队列数据结构,包含在队列中查找值的功能,相关实现及调用代码如下:

queue.cpp

LinkedListNode *CustomDataTypes::Queue::find_value(int value)
{
    auto found = false;
    auto current_node = head;

    try
    {
        if(current_node == nullptr){
            throw new std::runtime_error("Queue is empty");
        }

        // Sequentially check each node
        while (!found){   
            // Compare value
            if(current_node->value == value){
                found = true;
            }else{
                if(current_node->next != nullptr)
                {
                    // If not, then move on to the next node
                    auto next_node = current_node->next;
                    current_node = next_node;
                }else{
                    throw new std::runtime_error("Value does not exist in Queue");
                }
            }
        }
    }
    catch(const std::runtime_error& e)
    {
        std::cerr << "\n ERROR: " <<  e.what() << "\n\n";
    }
    
    // If correct, then return address of the node
    return current_node;
}

测试代码(main.cpp片段)

// GIVEN: Queue class is filled with 3 elements
auto new_queue = Queue();
new_queue.push_back(1);
new_queue.push_back(2);
new_queue.push_back(3);
.
.
// WHEN: Startup
// THEN: Attempts to find non-existing element in queue
EXPECT_THROW(new_queue.find_value(4), std::runtime_error);

测试报错

Expected: new_queue.find_value(4) throws an exception of type std::runtime_error.
  Actual: it throws a different type.

疑问

  1. 我哪里出错了?
  2. try和catch语句应该放在TEST作用域还是queue.cpp中?

解答

1. 错误原因

  • 抛出的是指针而非对象:你用throw new std::runtime_error(...)抛出的是std::runtime_error*类型的指针,但GTest的EXPECT_THROW期望捕获的是std::runtime_error对象,类型不匹配导致报错。C++异常处理中,通常直接抛出对象而非指针,正确写法是throw std::runtime_error("Queue is empty");。
  • 函数内部捕获了异常:find_value函数里的catch块已经把抛出的异常捕获并处理了,异常不会传递到测试代码中,GTest根本无法捕获到目标异常。

2. try/catch的放置建议

如果你的测试目标是验证函数在特定场景下会抛出异常,那么:

  • 不要在queue.cpp的find_value函数中加try/catch:让异常直接从函数抛出,这样测试代码才能通过EXPECT_THROW捕获到。
  • 测试代码中不需要手动加try/catch,GTest的EXPECT_THROW宏已经帮你处理了异常捕获和验证逻辑。

如果业务逻辑中需要对异常进行处理,那应该在调用find_value的业务代码中添加try/catch,而非在被测试的函数内部。


内容的提问来源于stack exchange,提问作者Arief Kurniawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 23:21:27