我还使用 GCov 来检查测试覆盖率(使用 Google 测试框架编写的测试),另外我使用 Eclipse GCov 集成插件或 LCov 工具来生成易于检查的测试覆盖率结果视图。原始的 GCov 输出太难使用了:-(。
如果您只有标头模板库,您还需要检测(使用 G++ 标志 --coverage)实例化模板类和模板成员函数的测试类,以查看这些的合理 GCov 输出。
使用上述工具,很容易发现根本没有用测试用例实例化的模板代码,因为它没有注释。
我已经设置了一个示例并将 LCov 输出复制到您可以检查的 DropBox 链接。
示例代码(TemplateSampleTest.cpp 使用 g++--coverage
选项检测):
模板示例.hpp
template<typename T>
class TemplateSample
{
public:
enum CodePath
{
Path1 ,
Path2 ,
Path3 ,
};
TemplateSample(const T& value)
: data(value)
{
}
int doSomething(CodePath path)
{
switch(path)
{
case Path1:
return 1;
case Path2:
return 2;
case Path3:
return 3;
default:
return 0;
}
return -1;
}
template<typename U>
U& returnRefParam(U& refParam)
{
instantiatedCode();
return refParam;
}
template<typename U, typename R>
R doSomethingElse(const U& param)
{
return static_cast<R>(data);
}
private:
void instantiatedCode()
{
int x = 5;
x = x * 10;
}
void neverInstantiatedCode()
{
int x = 5;
x = x * 10;
}
T data;
};
TemplateSampleTest.cpp
#include <string>
#include "gtest/gtest.h"
#include "TemplateSample.hpp"
class TemplateSampleTest : public ::testing::Test
{
public:
TemplateSampleTest()
: templateSample(5)
{
}
protected:
TemplateSample<int> templateSample;
private:
};
TEST_F(TemplateSampleTest,doSomethingPath1)
{
EXPECT_EQ(1,templateSample.doSomething(TemplateSample<int>::Path1));
}
TEST_F(TemplateSampleTest,doSomethingPath2)
{
EXPECT_EQ(2,templateSample.doSomething(TemplateSample<int>::Path2));
}
TEST_F(TemplateSampleTest,returnRefParam)
{
std::string stringValue = "Hello";
EXPECT_EQ(stringValue,templateSample.returnRefParam(stringValue));
}
TEST_F(TemplateSampleTest,doSomethingElse)
{
std::string stringValue = "Hello";
long value = templateSample.doSomethingElse<std::string,long>(stringValue);
EXPECT_EQ(5,value);
}
在此处查看 lcov 生成的代码覆盖率输出:
TemplateSample.hpp 覆盖率
警告:“函数”统计数据报告为 100%,对于未实例化的模板函数,这并不是真的。