如何使用google test写单元测试?

本博客 http://blog.csdn.net/livelylittlefish 贴出作者(三二一@小鱼)相关研究、学习内容所做的笔记,欢迎广大朋友指正!

Google test代码的编译很简单,那么,我们应该如何使用googletest来写单元测试呢?例如,要测一个函数,有哪些步骤?

 

The following text is extracted from ../samples/sample1_unittest.cc

// This sample shows how to write a simple unit test for a function,

// using Google C++ testing framework.

//

// Writing a unit test using Google C++ testing framework is easy as 1-2-3:

// Step 1. Include necessary header files such that the stuff your

// test logic needs is declared.

//

// Don't forget gtest.h, which declares the testing framework.

 

#include

#include "sample1.h"

#include

// Step 2. Use the TEST macro to define your tests.

//

// TEST has two parameters: the test case name and the test name.

// After using the macro, you should define your test logic between a

// pair of braces.  You can use a bunch of macros to indicate the

// success or failure of a test.  EXPECT_TRUE and EXPECT_EQ are

// examples of such macros.  For a complete list, see gtest.h.

//

//

//

// In Google Test, tests are grouped into test cases.  This is how we

// keep test code organized.  You should put logically related tests

// into the same test case.

//

// The test case name and the test name should both be valid C++

// identifiers.  And you should not use underscore (_) in the names.

//

// Google Test guarantees that each test you define is run exactly

// once, but it makes no guarantee on the order the tests are

// executed.  Therefore, you should write your tests in such a way

// that their results don't depend on their order.

//

//

// Step 3. Call RUN_ALL_TESTS() in main().

//

// We do this by linking in src/gtest_main.cc file, which consists of

// a main() function which calls RUN_ALL_TESTS() for us.

//

// This runs all the tests you've defined, prints the result, and

// returns 0 if successful, or 1 otherwise.

//

// Did you notice that we didn't register the tests?  The

// RUN_ALL_TESTS() macro magically knows about all the tests we

// defined.  Isn't this convenient?

Summary 3 个步骤
  1. 包含相应的头文件,尤其是gtest.h文件。
  2. TEST宏定义测试,如TEST(TestCaseName, TestName),其中使用EXPECT_EQ等语句定义具体测试。
  3. 调用RUN_ALL_TESTS(),实际上该函数不需要自己调用,只需要在编译、链接时将gtest-all.ccgtest_main.cc文件编译、链接到该工程即可。

 

Reference

http://code.google.com/p/googletest

http://www.cppprog.com/2009/0105/38.html

http://www.cnblogs.com/coderzh/archive/2009/04/06/1426755.html


Technorati 标签: 单元测试;google test

你可能感兴趣的:(单元测试,underscore,Google,Parameters,testing,googletest)