简体   繁体   中英

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

There is a library which is similar to 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. I am using visual studio 2013. I want good reference or any help to get start.

Using gtest is not very complicated and well documented .

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

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. 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.

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.

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:

#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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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