gtest_gtest测试静态函数

gtest_gtest测试静态函数GoogleTest在Ubuntu下的安装及编译:安装:sudoapt-getinstalllibgtest-devcd/usr/src/gtestsudocmake.sudomakesudomvlibg*/usr/lib/编译:假设源代码为sample.h和sample.cpp,测试代码为test.cppg++-csample.cppg++-ctest.c

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

###GoogleTest在Ubuntu下的安装及编译:
安装:

sudo apt-get install libgtest-dev
cd /usr/src/gtest
sudo cmake .
sudo make
sudo mv libg* /usr/lib/

编译:
假设源代码为sample.h和sample.cpp,测试代码为test.cpp

g++ -c sample.cpp
g++ -c test.cpp
g++ test.o sample.o -lgtest -o test -lpthread

###Assertions:
使用<<输出错误信息:

ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";

for (int i = 0; i < x.size(); ++i) {
  EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
}
Fatal assertion Nonfatal assertion Verifies
ASSERT_TRUE(condition); EXPECT_TRUE(condition); condition is true
ASSERT_FALSE(condition); EXPECT_FALSE(condition); condition is false
ASSERT_NE(val1,val2); EXPECT_NE(val1,val2); val1 != val2
ASSERT_LT(val1,val2); EXPECT_LT(val1,val2); val1 < val2
ASSERT_LE(val1,val2); EXPECT_LE(val1,val2); val1 <= val2
ASSERT_GT(val1,val2); EXPECT_GT(val1,val2); val1 > val2
ASSERT_GE(val1,val2); EXPECT_GE(val1,val2); val1 >= val2
ASSERT_STREQ(str1,str2); EXPECT_STREQ(str1,str2); the two C strings have the same content
ASSERT_STRNE(str1,str2); EXPECT_STRNE(str1,str2); the two C strings have different content
ASSERT_STRCASEEQ(str1,str2); EXPECT_STRCASEEQ(str1,str2); the two C strings have the same content, ignoring case
ASSERT_STRCASENE(str1,str2); EXPECT_STRCASENE(str1,str2); the two C strings have different content, ignoring case
ASSERT_FLOAT_EQ(val1, val2); EXPECT_FLOAT_EQ(val1, val2); the two float values are almost equal
ASSERT_DOUBLE_EQ(val1, val2); EXPECT_DOUBLE_EQ(val1, val2); the two double values are almost equal
ASSERT_NEAR(val1, val2, abs_error); EXPECT_NEAR(val1, val2, abs_error); the difference between val1 and val2 doesn’t exceed the given absolute error
ASSERT_THROW(statement, exception_type); EXPECT_THROW(statement, exception_type); statement throws an exception of the given type
ASSERT_ANY_THROW(statement); EXPECT_ANY_THROW(statement); statement throws an exception of any type
ASSERT_NO_THROW(statement); EXPECT_NO_THROW(statement); statement doesn’t throw any exception
ASSERT_PRED1(pred1, val1); EXPECT_PRED1(pred1, val1); pred1(val1) returns true
ASSERT_PRED2(pred2, val1, val2); EXPECT_PRED2(pred2, val1, val2); pred2(val1, val2) returns true

ASSERT_PRED例子:

// Returns true iff m and n have no common divisors except 1.
bool MutuallyPrime(int m, int n) { ... }
const int a = 3;
const int b = 4;
const int c = 10;
//EXPECT_PRED2(MutuallyPrime, a, b) succeed
//EXPECT_PRED2(MutuallyPrime, b, c) fail

注:
ASSERT_EQ比较两个字符串时,比较的是内存地址,如果只是想比较字符串的值,可以使用ASSERT_STREQ

###Simple Test:

Test(test_case_name, test_name) {
... test body ...
}

Test第一个参数为test_case的名字,第二个参数为test的名字,均需要符合c++命名方式且不能包含下划线,每个test的全名为test_case的名字加上自己本身的名字,不同的test_case下可以有相同名字的test。

###Test Fixtures:
继承于testing::Test,SetUp函数用来准备需要的数据,如果需要释放数据则在TearDown函数中,TEST_F中的第一个参数为类名,第二个为test的名字。
每个TEST_F为独立的
以下面代码为例,Test运行步骤:
1 新建一个QueueTest命名为t1
2 t1.SetUp()初始化
3 运行第一个Test,IsEmptyInitially
4 t1.TearDown()
5 t1自毁
6 重复以上步骤,执行的是Test,DequeueWorks

template <typename E> // E is the element type.
class Queue {
 public:
  Queue();
  void Enqueue(const E& element);
  E* Dequeue(); // Returns NULL if the queue is empty.
  size_t size() const;
  ...
};
class QueueTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    q1_.Enqueue(1);
    q2_.Enqueue(2);
    q2_.Enqueue(3);
  }

  // virtual void TearDown() {}

  Queue<int> q0_;
  Queue<int> q1_;
  Queue<int> q2_;
};
TEST_F(QueueTest, IsEmptyInitially) {
  EXPECT_EQ(0, q0_.size());
}

TEST_F(QueueTest, DequeueWorks) {
  int* n = q0_.Dequeue();
  EXPECT_EQ(NULL, n);

  n = q1_.Dequeue();
  ASSERT_TRUE(n != NULL);
  EXPECT_EQ(1, *n);
  EXPECT_EQ(0, q1_.size());
  delete n;

  n = q2_.Dequeue();
  ASSERT_TRUE(n != NULL);
  EXPECT_EQ(2, *n);
  EXPECT_EQ(1, q2_.size());
  delete n;
}

###Invoking the Tests:
RUN_ALL_TESTS():
1 保存gtest flag的状态
2 创建第一个test fixture
3 SetUp初始化
4 进行测试
5 TearDown销毁
6 删除fixture
7 restore gtest flag的状态
8 重复以上步骤,直到所有test执行完毕

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

###Sharing Resources Between Tests in the Same Test Case
不更改测试资源,则可以用SetUpTestCase函数和TearDownTestCase函数创建共享资源和删除共享资源。

class FooTest : public ::testing::Test {
 protected:
  // Per-test-case set-up.
  // Called before the first test in this test case.
  // Can be omitted if not needed.
  static void SetUpTestCase() {
    shared_resource_ = new ...;
  }

  // Per-test-case tear-down.
  // Called after the last test in this test case.
  // Can be omitted if not needed.
  static void TearDownTestCase() {
    delete shared_resource_;
    shared_resource_ = NULL;
  }

  // You can define per-test set-up and tear-down logic as usual.
  virtual void SetUp() { ... }
  virtual void TearDown() { ... }

  // Some expensive resource shared by all tests.
  static T* shared_resource_;
};

T* FooTest::shared_resource_ = NULL;

TEST_F(FooTest, Test1) {
  ... you can refer to shared_resource here ...
}
TEST_F(FooTest, Test2) {
  ... you can refer to shared_resource here ...
}

###Global Set-Up and Tear-Down
首先继承Environment类来定义一个测试环境,然后调用AddGlobalTestEnvironment函数,注册环境类的实例,当RUN_ALL_TEST执行时,首先调用环境对象的SetUp方法,所有测试结束之后调用环境变量的TearDown方法。

###Value Parameterized Tests
首先定义一个类继承自TestWithParamInterface<T>,或者直接继承于TestWithParam<T>即可,然后使用TEST_P定义测试内容,最后使用INSTANTIATE_TEST_CASE_P进行参数传递,INSTANTIATE_TEST_CASE_P第一个参数为test case的前缀,可以跨文件,第二个参数为test case的名称,需要和之前定义的类名称一样,第三个参数为参数生成器

Range(begin, end[, step]) Yields values {begin, begin+step, begin+step+step, ...}. The values do not include end. step defaults to 1.
Values(v1, v2, ..., vN) Yields values {v1, v2, ..., vN}.
ValuesIn(container) and ValuesIn(begin, end) Yields values from a C-style array, an STL-style container, or an iterator range [begin, end). container, begin, and end can be expressions whose values are determined at run time.
Bool() Yields sequence {false, true}.
Combine(g1, g2, ..., gN) Yields all combinations (the Cartesian product for the math savvy) of the values generated by the N generators. This is only available if your system provides the <tr1/tuple> header. If you are sure your system does, and Google Test disagrees, you can override it by defining GTEST_HAS_TR1_TUPLE=1. See comments in include/gtest/internal/gtest-port.h for more information.
class FooTest : public ::testing::TestWithParam<const char*> {
  // You can implement all the usual fixture class members here.
  // To access the test parameter, call GetParam() from class
  // TestWithParam<T>.
};

// Or, when you want to add parameters to a pre-existing fixture class:
class BaseTest : public ::testing::Test {
  ...
};
class BarTest : public BaseTest,
                public ::testing::WithParamInterface<const char*> {
  ...
};
TEST_P(FooTest, DoesBlah) {
  // Inside a test, access the test parameter with the GetParam() method
  // of the TestWithParam<T> class:
  EXPECT_TRUE(foo.Blah(GetParam()));
  ...
}

TEST_P(FooTest, HasBlahBlah) {
  ...
}
INSTANTIATE_TEST_CASE_P(InstantiationName,
                        FooTest,
                        ::testing::Values("meeny", "miny", "moe"));

###Running Test Programs: Advanced Options
--gtest_list_tests:列出所有测试名称
--gtest_filter:过滤器,仅运行全名与过滤器匹配的测试,格式为以”:“分隔的列表,可以在最后加一个”-“和”:”分隔的列表,表示负模式,*匹配任何字符串,?匹配任何单个字符。
DISABLED_:在每个测试名称前添加DISABLED_,或者添加在测试用例名称的前面,则这些测试将会被编译但是不会被运行。
--gtest_also_run_disabled_tests:执行被禁用的测试
--gtest_repeat=num:重复所有测试方法num次
--gtest_shuffle:洗牌测试
--gtest_output=xml[:DIRECTORY_PATH/|:FILE_PATH]

###Distributing Test Functions to Multiple Machines
分配多个shards进行测试,在每一个shard上,将GTEST_TOTAL_SHARDS设置为shard总数,所有shard上该设置相同,同时每一个shard上GTEST_SHARD_INDEX设置为索引,所有shard不同,且必须在0-(GTEST_TOTAL_SHARDS-1)范围内,所有测试函数在所有shard上,只运行一次

注:
FAIL* 和 ASSERT_为fatal error,所在的函数必须返回类型为void
如果函数必须要返回其他类型,则可以使用ADD_FAILURE
和 EXPECT_*

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/187757.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 感知机(Perceptron)为什么不能表示异或(XOR)

    感知机(Perceptron)为什么不能表示异或(XOR)1.感知机不能表示异或在很早之前学PatternRecognition相关课程的时候,老师在课堂上就说过感知机遇到的一个大问题就是无法表示异或问题(XOR)。后来接触深度学习相关的内容,开头部分肯定会提到感知机,提到感知机也必会提到不能表示异或的问题。正好抽出点时间,稍微搞明白一下为什么感知机不能表示异或。2.感知机的数学定义感知机到底是什么呢?首先来看一下他的数学定义:假设输入空间(即样本的

    2022年7月16日
    14
  • 学习入侵躲避技术—理解AET

    学习入侵躲避技术—理解AET

    2022年3月11日
    36
  • tcpdump抓包命令详解_tcpdump抓udp包命令详解

    tcpdump抓包命令详解_tcpdump抓udp包命令详解linux抓包-tcpdump命令:enp4s0f0—ifconfig—>网卡名称-s0—->不限制抓包的大小port25228—->只抓取服务器上25228端口的数据流量-whk2.pcap—>保存的文件名称-v—>显示抓包的大小数字

    2022年8月20日
    6
  • android删除自带应用程序,安卓手机自带软件怎么卸载?无需root卸载安卓手机自带软件方法…

    android删除自带应用程序,安卓手机自带软件怎么卸载?无需root卸载安卓手机自带软件方法…当我们入手一台新安卓手机的时候 会发现里面有很多预装应用 而且我们并不常用 那么安卓手机自带软件怎么卸载呢 今天绿茶小编就为大家介绍无需 root 卸载安卓手机自带软件的方法 25 55MB 手机工具刷机精灵提供的卸载预装应用功能 通过简单的操作 让用户轻松卸载手机自带应用 释放内存空间 加速手机系统 延长手机待机时间 避免恶意软件产生的恶意扣费 恶意扣流量 甚至窃取用户个人隐私等危害 使用步骤如

    2025年7月16日
    0
  • 近两万字小程序攻略发布了

    近两万字小程序攻略发布了

    2021年6月12日
    133
  • 基于stm32的室内环境监测系统设计及实现_毕业设计怎么做

    基于stm32的室内环境监测系统设计及实现_毕业设计怎么做一、前言这是本科时的毕业设计,想着之后读研了,研究方向是机器学习了,可能不会这么再碰32或者51之类的板子了,就想趁着还没有忘记就来梳理一下,纪念陪伴了我两年的硬件朋友们,作为的一个足迹。二、项目背景及资源分享这次毕业设计的灵感来源于20年的电赛,当时因为考研时间紧张的原因,在做一个《无线传感器结点》题目的时候,当时是使用的无线传感器模块讲数据传到电脑作为一个上位机的展示。但当时想做的是使用wifi模块来实现无线传输功能,传到一个自己写的web服务器,在页面上进行展示的,由于时间原因最终还是选择了前者

    2022年9月1日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号