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_*

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

发表回复

您的电子邮箱地址不会被公开。

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