【问题标题】:how to get per test coverage for google tests c++ with gcov (or other free tool)如何使用 gcov(或其他免费工具)获得谷歌测试 C++ 的每个测试覆盖率
【发布时间】:2021-11-26 17:21:31
【问题描述】:

我想为我的 c++ 程序中的每个测试用例获取每个测试覆盖率。

我得到的是 GoogleTest 允许在每次测试之前和之后执行一些操作

#pragma once
#include <gtest/gtest.h>
#include <gcov.h>
class CodeCoverageListener : public ::testing::TestEventListener
{
public:
    virtual void OnTestProgramStart(const ::testing::UnitTest&) {}
    virtual void OnTestIterationStart(const ::testing::UnitTest&, int) {}
    virtual void OnEnvironmentsSetUpStart(const ::testing::UnitTest&) {}
    virtual void OnEnvironmentsSetUpEnd(const ::testing::UnitTest&) {}
    virtual void OnTestCaseStart(const ::testing::TestCase&) {}
    virtual void OnTestPartResult(const ::testing::TestPartResult&) {}
    virtual void OnTestCaseEnd(const ::testing::TestCase&) {}
    virtual void OnEnvironmentsTearDownStart(const ::testing::UnitTest&) {}
    virtual void OnEnvironmentsTearDownEnd(const ::testing::UnitTest&) {}
    virtual void OnTestIterationEnd(const ::testing::UnitTest&, int) {}
    virtual void OnTestProgramEnd(const ::testing::UnitTest&) {}

    virtual void OnTestStart(const ::testing::TestInfo& test_info)
    {
        __gcov_reset();
    }

    virtual void OnTestEnd(const ::testing::TestInfo& test_info)
    {
       __gcov_dump();
    }
};

然后你告诉 GoogleTest 这件事

 ::testing::UnitTest::GetInstance()->listeners()
        .Append(new CodeCoverageListener);

但是在使用 gcc4.8.5 编译时出现错误:

 fatal error: gcov.h: No such file or directory
 #include <gcov.h>

如何告诉 gcc 在哪里寻找这个包含?

在使用 gcc8.4.1 编译期间出现链接器错误:

 g++ -lgcov gcov.cpp
/tmp/ccK7o95R.o: In function `main':
gcov.cpp:(.text+0x5): undefined reference to `__gcov_reset()'
collect2: error: ld returned 1 exit status

如何将gcov链接到c++程序?

【问题讨论】:

    标签: c++ gcov


    【解决方案1】:

    gcov.h 标头是 GCC 内部的,因此它没有安装在任何包含路径中。如果您想自己调用 gcov 函数(我不建议这样做),那么您必须自己声明它们。

    extern void __gcov_reset (void);
    extern void __gcov_dump (void);
    

    libgcov 链接应该可以工作,但需要注意的是它是一个静态库。

    【讨论】:

    • 为什么不推荐这个?我在在线手册上找到了它gcc.gnu.org/onlinedocs/gcc/…
    • @dobrowol 这些函数已记录在案且稳定,但不会直接执行您期望它们执行的操作。重要的是,您必须重命名/移动生成的 gcda 文件,因为转储函数将覆盖现有数据文件。通过检测单个测试,您还将错过静态初始化和销毁​​的覆盖率数据,这在 C++ 程序中可能非常相关。
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2017-04-09
    • 2018-02-08
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    相关资源
    最近更新 更多