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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • python mkv转mp4,如何将mkv格式转换成mp4视频呢

    python mkv转mp4,如何将mkv格式转换成mp4视频呢在日常生活中都会使用到MKV视频文件的。MKV视频文件主要是视频文件、音频文件和字幕压制的。MKV视频一般在网上都是可以直接下载的。各种种子和磁链下载的也基本都是MKV视频。但有时可能会碰到视频播放错误。无法播放或者不支持文件播放的。一般都是可以通过转换视频格式修改的。那今天就教大家怎么将mkv格式转换成mp4格式吧。1、首先点击下方的立即下载按钮然后弹出下载迅捷视频转换器的下载框。下载打开之后,…

    2022年10月16日
    4
  • 一篇文章让你了解Hive和HBase的区别

    相信做大数据开发的朋友对hive和HBase一定不会陌生。HBASE想了解更多大数据相关知识可以点击“了解更多”Hive是基于Hadoop的一个数据仓库工具,可以将结构化的数据文件映射为一张数据库表,并提供简单的sql查询功能,可以将sql语句转换为MapReduce任务进行运行。HBase是Hadoop的数据库,一个分布式、可扩展、大数据的存储。单个的从字面意思上或许很难看出二者…

    2022年4月9日
    56
  • 使用sp_executesql存储过程执行动态SQL查询

    使用sp_executesql存储过程执行动态SQL查询Thesp_executesqlstoredprocedureisusedtoexecutedynamicSQLqueriesinSQLServer.AdynamicSQLqueryisaqueryinstringformat.ThereareseveralscenarioswhereyouhaveanSQLq…

    2022年5月21日
    31
  • vs2012 webservice 实例

    vs2012 webservice 实例1.把安装好的VS打开

    2022年7月21日
    16
  • 同居第60天,在家族群里目睹了男友劈腿全过程……我笑抽了哈哈哈!

    文案改编自:新青年大院NEWYOUTH。这里有全网最奇葩的情感故事,这里有你想不到的憨批投稿,这里有你和你身边朋友的影子,也有你恨的牙痒痒的各种痴男怨女。总之,这是一个关注了就停不…

    2021年6月21日
    91
  • 360自动拦截的防护怎么修改_微信屏蔽投诉按钮代码

    360自动拦截的防护怎么修改_微信屏蔽投诉按钮代码个人有各自不同的编写方法。不必拘泥一格。只要了解原理是访问首页,运行js文件,在JS文件里面调用一个文件,显示网站。JS的写法有很多,比如还有下面的写法:document.write(unescape(unescape(unescape(unescape(unescape(‘%252525253Cframeset%2525252520rows%252525253D%2525252522*%

    2025年6月9日
    2

发表回复

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

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