[英]What is the correct way to set up a UnitTest project for C++ in Visual Studio with additional include directories in the main Project?
I am trying to test a C++ Project in Visual Studio 2019.我正在尝试在 Visual Studio 2019 中测试 C++ 项目。
The project, which should be tested, has a class MyClass.应该测试的项目有一个类 MyClass。 The project folder has a directory "include" and I did set up the path in Properties > C/C++ > General > Additional include directory .项目文件夹有一个目录“include”,我确实在Properties > C/C++ > General > Additional include directory 中设置了路径。
MyClass.h:我的类.h:
#pragma once
#include <string>
class MyClass
{
public:
void print() const;
};
MyClass.cpp:我的类.cpp:
#include "MyClass.h"
void MyClass::print() const {
printf("MyClass print");
}
This code executes just fine.这段代码执行得很好。
Now when I try to test this solution with a new UnitTest Project in the same solution I have some problems how to include MyClass and to test it there.现在,当我尝试在同一解决方案中使用新的 UnitTest 项目测试此解决方案时,我遇到了一些问题,即如何包含 MyClass 并在那里对其进行测试。
I included the reference to the first project in my UnitTest Project.我在我的 UnitTest 项目中包含了对第一个项目的引用。
Variant 1 in UnitTest1.cpp: UnitTest1.cpp 中的变体 1:
#include "..\ConsoleApplication1\include\MyClass.h"
#include "..\ConsoleApplication1\MyClass.cpp"
Result: Error C2011 -> "MyClass": class type new definition结果:错误 C2011 ->“MyClass”:类类型新定义
Error C2027 -> Use of undefined type "MyClass"错误 C2027 -> 使用未定义的类型“MyClass”
Error C2070 -> "print": Modifiers not allowed on nonmember functions错误 C2070 ->“打印”:非成员函数上不允许使用修饰符
Error C2079 -> undefined Class "MyClass"错误 C2079 -> 未定义的类“MyClass”
Variant 2 in UnitTest.cpp: UnitTest.cpp 中的变体 2:
#include "..\ConsoleApplication1\include\MyClass.h"
Result: Error LNK2019, 1120 unresolved externals结果:错误 LNK2019,1120 未解析的外部
I believe this is because of the additional include directory in the main project.我相信这是因为主项目中有额外的包含目录。 Without additional include directory and with "#include "include\\MyClass.h" in MyClass.cpp, the UnitTest works correctly . How do i include the Classes from the origninal project into the UnitTest Project properly?没有额外的包含目录和 MyClass.cpp 中的“#include”include\\MyClass.h,UnitTest 可以正常工作。如何将原始项目中的类正确地包含到 UnitTest 项目中?
您必须将 MyClass.cpp 添加到测试项目的源中。
The solution is to also add the same "include" folder from the first project to Properties > C/C++ > General > Additional include directory in the TestUnit Project .解决方案是还将第一个项目中相同的“include”文件夹添加到TestUnit Project中的Properties > C/C++ > General > Additional include 目录。
Then I can add然后我可以添加
#include "MyClass.h"
#include "..\ConsoleApplication1\MyClass.cpp"
to the TestUnit1.cpp file and use the class MyClass correctly.到 TestUnit1.cpp 文件并正确使用类 MyClass。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.