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.