Out-of-the-box security-unit testing in C ++

Source: Internet
Author: User

This article introduces the implementation of unit test in C ++ development. I have referred to the unit test code automatically generated by netbeans.

First, define the macro in the general header file:

#define _QSW_TEST #ifdef _QSW_TEST    #define DLog(...) printf(__VA_ARGS__);printf("\n")#else    #define Dlog(...)#endif

Define dlog macro functions. In the test environment, dlog is equivalent to adding a carriage return after printf. In order to write less \ n for dlog, the carriage return is added, but this also limits the use of freedom-you can only use dlog macro functions as empty functions, instead of using the return value of the printf function-it is not actually used.

In OOP languages such as C ++, unit testing units are classes, such as weather classes, or member functions of classes such as weather. rain () (when will the rain in Hangzhou stop ......). There are three requirements for the weather test function:

1) switch the test environment and non-test environment only by commenting # DEFINE _ qsw_test.

2) test should be a public member function of weather when it can access weather ).

3) Calling the test operation does not affect weather, nor create a new weather object (So test is a static function ).

For example:

class FilePathManager{public:    ~FilePathManager();        static FilePathManager *SharedInstancePointer();     #ifdef _QSW_TEST    static void Test();#endif    private:    inline FilePathManager();    static FilePathManager *p_shared_instance_;};

Create a new test file for this class, such as filepathmanager_test.cpp. In this file:

#ifdef _QSW_TEST#include "FilePathManager.h"void FilePathManager::Test(){    FilePathManager *m = FilePathManager::SharedInstancePointer();}#endif

In the main function file, you can use macro-defined methods to switch between different main functions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.