Google Test Sample04
一、环境信息
- Visual Studio 2019
- Windows 10
二、Google Test Sample04
1. 示例概述
1.1 sample04讲解的是如何测试计数器,但示例中并没有新内容,本质还是类的单元测试
1.2 头文件内容
class Counter
{
private:
int counter_;
public:
// Creates a counter that starts at 0.
Counter() : counter_(0) {} //构造函数
// Returns the current counter value, and increments it.
int Increment(); //先返回当前值,再改变
// Returns the current counter value, and decrements it.
int Decrement();
// Prints the current counter value to STDOUT.
void Print() const;
};
1.3 配套的cpp文件
#include "sample04.h" //定义了类Counter
// Returns the current counter value, and increments it.
int Counter::Increment()
{
return counter_++;//先赋值 再加1
}
// Returns the current counter value, and decrements it.
// counter can not be less than 0, return 0 in this case
int Counter::Decrement()
{
if (counter_ == 0) { //为0时返回0,不再减
return counter_;
}
else {
return counter_--;//先赋值 再减1
}
}
// Prints the current counter value to STDOUT.
void Counter::Print() const {
cout << counter_;//printf("%d", counter_);
}
2. 单元测试用例
2.1 没有什么新内容,还是TEST宏的应用
2.2 除Counter::Print()函数外,其余函数已在单元测试用例中覆盖
TEST(CounterTest, Increment)
{
Counter c;
// Test that counter 0 returns 0
EXPECT_EQ(0, c.Decrement());
// EXPECT_EQ() evaluates its arguments exactly once, so they can have side effects.
EXPECT_EQ(0, c.Increment());
EXPECT_EQ(1, c.Increment());
EXPECT_EQ(2, c.Increment());
EXPECT_EQ(3, c.Decrement());
}
3.如影随形的编译错误(已解决)
3.1 头文件、cpp文件 与 单元测试文件 分属不同文件时,仍然会出现相同的报错,究竟是哪儿没对呢
TEST(CounterTest, Increment)
{
Counter c;
}
3.2 原因分析及解决方法
3.2.1 原因分析:通过对比测试发现,sample04UnitTest.cpp包含了多个头文件(如下所示),当sample04.h位于pch.h的下方时,编译时一定会触发上述报错
#include "sample04.h"
#include "pch.h"
3.2.2 解决方法:调整sample04.h的位置,将其调整到pch.h的下方。根因还不清楚(可能和vs2019强相关),但是当前方法足以解决我目前遇到的问题
#include "pch.h"
#include "sample04.h"
namespace
{
// Tests the Increment() method.
TEST(CounterTest, Increment)
{
Counter c;
// Test that counter 0 returns 0
EXPECT_EQ(0, c.Decrement());
EXPECT_EQ() evaluates its arguments exactly once, so they can have side effects.
EXPECT_EQ(0, c.Increment());
EXPECT_EQ(1, c.Increment());
EXPECT_EQ(2, c.Increment());
EXPECT_EQ(3, c.Decrement());
}
} // namespace