GoogleTest - 事件监听器



GoogleTest 中的事件监听器是一个 API,允许您接收有关测试程序进度及其成功和失败的通知。使用此 API,您可以接收各种事件的通知,例如测试程序、测试套件或测试方法的开始和结束等。

此外,它还可以帮助您将标准控制台输出替换为 XML 输出,或提供完全不同的输出格式,例如 GUI 或数据库。

GoogleTest 中的每个事件都与一个处理程序函数相关联。当事件触发时,其上下文将作为参数传递给这些函数。参数类型如下:

  • UnitTest − 它表示整个测试程序的状态。
  • TestSuite − 它提供有关测试套件的信息。
  • TestInfo − 它包含单个测试的状态。
  • TestPartResult − 它表示测试断言的结果。

定义事件监听器

在 GoogleTest 中,可以通过继承 testing::TestEventListener 接口或 testing::EmptyTestEventListener 接口来定义事件监听器。

TestEventListener 接口

TestEventListener 接口用于跟踪测试的执行。它提供以下列出的虚拟方法,可以覆盖这些方法来处理测试事件:

  • OnTestProgramStart − 此方法在任何活动开始之前触发。
  • OnTestIterationStart − 在每次测试迭代开始之前触发。
  • OnEnvironmentsSetUpStart − 在每次测试迭代的环境设置开始之前触发。
  • OnEnvironmentsSetUpEnd − 在每次测试迭代的环境设置结束之后触发。
  • OnTestSuiteStart − 在测试套件开始之前调用。
  • OnTestEnd − 当指定的测试结束时触发。

EmptyTestEventListener 接口

GoogleTest 中的 EmptyTestEventListener 接口提供了 TestEventListener 接口中所有方法的空实现。要使用它,您只需覆盖这些方法即可。

如何使用已定义的事件监听器

要使用您定义的事件监听器,请在调用 RUN_ALL_TESTS() 之前,将它的实例添加到 main() 函数中的 GoogleTest 事件监听器列表中。此事件监听器列表由TestEventListeners 类表示。

示例

让我们看看如何在 GoogleTest 中编写事件监听器。

#include <gtest/gtest.h>
#include <iostream>

class FirstTestEventListener : public ::testing::EmptyTestEventListener {
    // Called before a test starts
    void OnTestStart(const ::testing::TestInfo& test_info) override {
        std::cout << "test is starting : " << test_info.name() << std::endl;
    }

    // Called after a test ends
    void OnTestEnd(const ::testing::TestInfo& test_info) override {
        std::cout << "test finished : " << test_info.name() << std::endl;
    }
};

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);

    // Create and register the custom test event listener
    ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance() -> listeners();
    listeners.Append(new FirstTestEventListener);

    int result = RUN_ALL_TESTS();
}

这段代码不会产生任何输出,因为我们没有给出任何测试。

广告
© . All rights reserved.