您絕對希望您的測試代碼與您的測試代碼分離。你並不想讓你的代碼在測試代碼上有任何依賴關係。
在任何規模的項目中,您可能都希望使用unit testing framework在單獨的程序集/庫中編寫測試,但對於足夠小的事情,可以考慮通過將命令行參數傳遞給主函數來運行所有測試。下面是一個簡單的荒謬例如:
Greeting.h:
#pragma once
#include <string>
std::string getGreeting();
Greeting.cpp:
#include "Greeting.h"
std::string getGreeting() {
return "Hello world!";
}
Test.h:
#pragma once
void test();
Test.cpp的:
#include "Test.h"
#include "Greeting.h"
#include <cassert>
#include <iostream>
void test() {
auto greeting = getGreeting();
assert(greeting == "Hello world!");
std::cout << "Test passes!\n";
}
main.cpp中:
#include "Test.h"
#include "Greeting.h"
#include <iostream>
void run() {
std::cout << getGreeting() << "\n";
}
int main(int argc, char *argv[]) {
if (argc > 1 && strcmp(argv[1], "-t") == 0)
test();
else
run();
}
Live demo
恕我直言,你的問題是相當過於寬泛。 – 101010 2014-09-23 16:55:33
有趣的是,我不明白我怎麼能更具體,但我會努力成爲。我在問在定義類時人們應該如何努力測試他們的代碼。顯然,如果令牌永遠不會被其他任何東西使用,我可以在Token.cpp中用main()來測試。但是如果我要在其他文件中使用Token,那麼也會有一個main(),Token.cpp中的main()會不會導致問題? – user2386276 2014-09-23 16:58:45
這是Microsoft Visual Studio 2013關於使用C++進行單元測試的資料http://msdn.microsoft.com/zh-cn/library/hh598953.aspx作爲單元測試,它聽起來就像您想要做的一樣。您需要花一些時間閱讀C++中的單元測試。如果你想在某個類中加入main()函數,你應該使用預處理器指令來#ifdef它,而不是註釋掉它。另請參閱http://stackoverflow.com/questions/87794/c-unit-testing-framework和http://stackoverflow.com/questions/242926/comparison-of-c-unit-test-frameworks – 2014-09-23 16:59:14