简体   繁体   English

如何使用Google Test为cpp库编写单元测试

[英]How to write unit test for a cpp library already exist using google test

There is a library which is similar to libxml2. 有一个类似于libxml2的库。 It is already exist. 它已经存在。 I don't going to create a new library. 我不会创建一个新的库。 I want to unit test above existing library using google test. 我想使用Google测试对现有库进行单元测试。 I am using visual studio 2013. I want good reference or any help to get start. 我正在使用Visual Studio2013。我需要良好的参考或任何帮助来开始使用。

Using gtest is not very complicated and well documented . 使用gtest并不是很复杂并且有充分的文件记载

Setting up the build 设置构建

The main surprising stuff is how to use it in your project. 令人惊讶的主要内容是如何在项目中使用它。 The "official" way is to copy the whole repository in your sources. “官方”方式是在源中复制整个存储库。

You can for example create a googletest subdirectory in your project by cloning: https://github.com/google/googletest.git 例如,您可以通过克隆在项目中创建googletest子目录: https : //github.com/google/googletest.git

Then you need to add it in the build of your project. 然后,您需要将其添加到项目的构建中。 This is dependent of the buildsystem you use and the platform you're on. 这取决于您使用的构建系统和所使用的平台。 I don't know about Visual Studio but this should be easy to adapt. 我对Visual Studio不了解,但这应该很容易适应。 You'll need to expand your include path (you can do it only for the test objects): 您需要扩展包含路径(只能对测试对象执行此操作):

TEST_CFLAGS=-I$(GTEST_DIR)/include -I$(GTEST_DIR)

And add gtest-all.o (or the equivalent on Windows) in the objects to be linked with your test. 并在要与测试链接的对象中添加gtest-all.o (或Windows上的等效项)。

You will have to create a new target also as your unit-tests will be launched by a binary. 您还必须创建一个新目标,因为您的单元测试将由二进制文件启动。 Again, I'm not sure how to handle it with Visual Studio but this should be something easy for a regular user. 同样,我不确定如何使用Visual Studio处理它,但是对于普通用户来说应该很容易。

Writing tests 编写测试

Starting to write tests is easy. 开始编写测试很容易。 Writing good tests however is hard and I won't cover it, there are plenty of good books , websites but most of all, it takes practice and time. 但是,编写好的测试很困难,我也不会介绍,有很多好的书籍网站,但最重要的是,这需要实践和时间。

To write your first test, you will need a main file (let's say main.cc) that is very easy to write: 要编写您的第一个测试,您将需要一个非常容易编写的主文件(例如main.cc):

#include <gtest/gtest.h>

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

A good place to start is to look at examples . 一个很好的起点是看例子 Then you can follow the primer in gtest doc to have a good idea of basic features. 然后,您可以按照gtest doc中的入门知识,对基本功能有所了解。 If you feel you need more, you can have a look at advanced guide . 如果您觉得自己需要更多,可以阅读高级指南

Final word 最后的话

Good luck in your journey in unit testing and (hopefully) test-driven development. 祝您单元测试和(希望)测试驱动的开发旅途顺利。 This may be hard at the beginning. 一开始这可能很难。 Don't give-up to fast, the reward is huge. 不要放弃快速,回报是巨大的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM