gtest基础使用07:Google Test自带示例四:Counter

一、环境信息

  1. Visual Studio 2019
  2. 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

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值