在CMake工程頂層目錄內的CMakeLists.txt檔案中添加最後一行,使得目錄結構中包含test目錄,並且編譯完成時會在build目錄下產生test_bin目錄。
cmake_minimum_required(VERSION 2.8)project (your_project_name)add_subdirectory(src bin)add_subdirectory(test test_bin)
step2
在test目錄下的CMakeLists.txt檔案中就像src目錄下的一樣配置,你需要什麼庫,就加在裡面。不過需要一點下面的設定
include(CheckFunctionExists)include(CheckCXXSourceCompiles)include(CheckLibraryExists)include(CPack)enable_testing()...add_test(name your_test command your_test)
step3
test目錄下建立一個main函數,裡面編寫測試代碼,我嘗試著使用boost的test架構,暫時還沒有成功,因此使用了一個宏(來源於CppCMS的作者Artyom)
///////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008-2010 Artyom Beilis (Tonkikh) <artyomtnk@yahoo.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by// the Free Software Foundation, either version 3 of the License, or// (at your option) any later version.//// This program is distributed in the hope that it will be useful,// but WITHOUT ANY WARRANTY; without even the implied warranty of// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the// GNU Lesser General Public License for more details.//// You should have received a copy of the GNU Lesser General Public License// along with this program. If not, see <http://www.gnu.org/licenses/>./////////////////////////////////////////////////////////////////////////////////#ifndef CPPCMS_TEST_H#define CPPCMS_TEST_H#include <stdexcept>#include <sstream>#define TEST(X) \do {\if(X) break;\std::ostringstream oss;\oss << "Error " << __FILE__ << ":"<<__LINE__ << " "<<#X;\throw std::runtime_error(oss.str());\}while(0)#endif
使用這個宏很簡單,比如:
TEST(result >= 66);
step4
進入build目錄編譯,編譯成功後,進入test_bin目錄運行ctest,螢幕上會看到一些簡要的結果資訊:
Test project /home/chenshu/work/CommonService/trunk/c++/PipeLine2/build/test_bin Start 1: similarity_test1/1 Test #1: similarity_test ..................***Failed 0.31 sec0% tests passed, 1 tests failed out of 1Total Test time (real) = 0.89 secThe following tests FAILED: 1 - similarity_test (Failed)Errors while running CTest
並且會產生Testing/Temporary/目錄,該目錄下包含了幾個檔案,CTestCostData.txt LastTest.log LastTestsFailed.log,詳細測試資訊都在其中。