google test 例子 & coding style

来源:互联网 发布:19的网络语啥意思 编辑:程序博客网 时间:2024/06/05 03:36

google test & mock:

编写单元测试是非常有用的,良好的单元测试能够极大地减少代码中bug,尤其是当多人协作时,谁用谁知道啊!

自从 google code 关闭之后,gtest 被挪到了 github 中,不翻墙可以浏览了:-)

一个最简单的例子:

#include "gtest/gtest.h"// TEST宏需要两个字符串,在输出的时候能看到测试的是哪个caseTEST(MySimpleTest, PlusTest) {     int a = 1;     int b = a+1;     ASSERT_TRUE( b == a+1);     EXPECT_EQ (b, 3);}int main(int argc, char **argv) {  ::testing::InitGoogleTest(&argc, argv);  return RUN_ALL_TESTS();}

运行结果,ASSERT_TRUE通过测试,EXPECT_EQ 失败,所以测试 Failed 了,名字是 MySimpleTest.PlusTest

运行结果,第一个ASSERT_TRUE通过测试,第二个EXPECT_EQ 失败

修改为 EXPECT_EQ (b, 2);, 再次编译运行,测试通过了:

这里写图片描述

编译后的执行程序可以加上一些参数运行(重复测试次数,颜色等等),可以通过 ./my_simple_test --help 查看一下。


如果是复杂点的测试,例如需要初始化,清理等工作,可以使用这个:

class myTestCase: public ::testing::test { public:    myTestFixture1( ) {        // initialization code here   }    void SetUp( ) {        // code here will execute just before the test ensues    }   void TearDown( ) {        // code here will be called just after the test completes       // ok to through exceptions from here if need be   }   ~myTestFixture1( )  {        // cleanup any pending stuff, but no exceptions allowed   }   // put in any custom data members that you need };// 然后使用 TEST_F 宏进行测试(不是TEST宏)TEST_F (myTestCase, Unit1) {    …}TEST_F (myTestCase, Unit2) {    …}int main(int argc, char **argv) {  ::testing::InitGoogleTest(&argc, argv);  return RUN_ALL_TESTS();}

一堆宏,mark一下以方便用时浏览:
https://github.com/google/googletest/blob/master/googletest/docs/Primer.md

谷歌coding style:

http://google.github.io/styleguide/cppguide.html

0 0
原创粉丝点击