【发布时间】:2018-02-09 21:51:01
【问题描述】:
我是单元测试的新手,并决定使用 Catch 框架用于 c++,因为它似乎很容易与其一个头文件集成。但是,我有一个多文件二叉搜索树程序(文件有:main.cpp、Tree.h、Tree.hxx、TreeUnitTests.cpp、catch.hpp)。如果我在 main.cpp 中注释掉我的 int main() 函数,我只能让我的单元测试运行。我知道它与我的 TreeUnitTests.cpp 中的“#define CATCH_CONFIG_MAIN”声明冲突,但如果我不包含该声明,我将无法运行单元测试。每次我想运行单元测试时,如何在不必注释 main() 的情况下让两者都运行?
这是我正在使用的头文件: https://raw.githubusercontent.com/philsquared/Catch/master/single_include/catch.hpp
我在 Catch 教程中找到并用作指南: https://github.com/philsquared/Catch/blob/master/docs/tutorial.md
一些相关文件供参考: main.cpp:
//******************* ASSN 01 QUESTION 02 **********************
#include "Tree.h"
#include <iostream>
using namespace std;
/*
int main()
{
//creating tree with "5" as root
Tree<int> tree(5);
tree.insert(2);
tree.insert(88);
tree.inorder();
cout << "does tree contain 2?: ";
cout << tree.find(2) << endl;
cout << "does tree contain 3?: ";
cout << tree.find(3) << endl;
Tree<int> copytree(tree);
cout << "copied original tree..." << endl;
copytree.preorder();
cout << "after deletion of 2:\n";
copytree.Delete(2);
copytree.postorder();
return 0;
}
*/
TreeUnitTests.cpp:
#include <iostream>
#include "Tree.h"
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
TEST_CASE("Pass Tests")
{
REQUIRE(1 == 1);
}
TEST_CASE("Fail test")
{
REQUIRE(1 == 0);
}
(我的测试不是真正的测试,只是为了验证 Catch 框架是否正常工作。我猜你可以说这是一个元测试)
【问题讨论】:
-
您是否将其全部链接到一个可执行文件中?为什么?
-
你不应该用测试程序编译你的
main.cpp。测试程序有自己的main()。 -
您应该有一个单独的构建用于单元测试,不包括
main.cpp文件。或者,这个单独的构建可以创建一个定义(例如#define UNIT_TESTING),它可以用于有条件地从main.cpp中仅删除main()函数(以防它包含其他可测试的函数)。 -
我没有意识到我不应该用测试程序编译 main.cpp。我如何不一起编译它,因为它都在 Visual Studios 的同一个项目文件夹中?我怎样才能创建这个单独的构建? (澄清一下,main.cpp 和 TreeUnitTests.cpp 都在 Source 文件夹下,Tree.h 和 Tree.hxx 在 Header 文件夹下。这两个文件夹都在同一个项目文件夹中)你还可以提供更多对所提到的#define UNIT_TESTING 定义的见解?
-
P.S. catch.hpp 也在 Header 文件夹下。
标签: c++ unit-testing catch-unit-test