单元测试类无法在我要测试的同一解决方案中的另一个项目中找到类

Unit test class unable to find class in another project in the same solution i want to test

本文关键字:另一个 单元测试 解决方案 项目 我要 单元 测试 测试类      更新时间:2023-10-16

我正在尝试对解决方案(我们称之为Project1(中的一个项目中的类执行一些基本的单元测试(我们称之为Project1(在c ++中的另一个单元测试项目(我们称之为UnitTest1(。我使用的是最新版本的Visual Studio 2019。

我在 Visual Studio 2019 中为 c++ 创建了一个全新的解决方案,并在另一个文件中添加了一个带有类 HelloWorld 的控制台应用程序,该文件只有一个返回 std::string "Hello World" 的方法。

然后,我在解决方案中添加了一个新的"本机单元测试项目",在引用下添加了 Project1 控制台应用程序,并键入代码,如下所示:

项目1 文件:

#include <iostream>
#include "HelloWorld.h"
int main() {
HelloWorld* hello = new HelloWorld();
std::cout << hello->sayHello();
}

你好世界:

#pragma once
#include <string>
class HelloWorld {
public: HelloWorld();
public: std::string sayHello();
};

你好世界.cpp:

#include "HelloWorld.h"
#include <string>
HelloWorld::HelloWorld() {
}
std::string HelloWorld::sayHello() {
return std::string("Hello World");
}

单元测试1.cpp:

#include "pch.h"
#include "CppUnitTest.h"
#include "..//ConsoleApplication1/HelloWorld.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1 {
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1)
{
HelloWorld* hello = new HelloWorld();
Assert::AreEqual(hello->sayHello(), std::string("Hello World"));
}
};
}

当我尝试通过测试资源管理器运行测试时,我得到:

1>------ Build started: Project: UnitTest1, Configuration: Debug Win32 ------
1>pch.cpp
1>UnitTest1.cpp
1>   Creating library C:UsersIblobsourcereposConsoleApplication1DebugUnitTest1.lib and object C:UsersIblobsourcereposConsoleApplication1DebugUnitTest1.exp
1>UnitTest1.obj : error LNK2019: unresolved external symbol "public: __thiscall HelloWorld::HelloWorld(void)" (??0HelloWorld@@QAE@XZ) referenced in function "public: void __thiscall UnitTest1::UnitTest1::TestMethod1(void)" (?TestMethod1@UnitTest1@1@QAEXXZ)
1>UnitTest1.obj : error LNK2019: unresolved external symbol "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall HelloWorld::sayHello(void)" (?sayHello@HelloWorld@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) referenced in function "public: void __thiscall UnitTest1::UnitTest1::TestMethod1(void)" (?TestMethod1@UnitTest1@1@QAEXXZ)
1>C:UsersIblobsourcereposConsoleApplication1DebugUnitTest1.dll : fatal error LNK1120: 2 unresolved externals
1>Done building project "UnitTest1.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 1 up-to-date, 0 skipped ==========

我希望链接器应该能够找到根据微软自己的教程引用的文件:https://learn.microsoft.com/en-us/visualstudio/test/writing-unit-tests-for-c-cpp?view=vs-2019

我尝试将类标头和 cpp 作为现有项目添加到我的单元测试项目中,但是当我尝试运行测试时,它只是尝试在 HelloWorld 类中找到 #include"pch.h"。

我在这里缺少什么来告诉链接器在哪里可以找到类符号?

添加 #include "..控制台应用程序1/HelloWorld.cpp"到我的unitTest1.cpp文件似乎已经修复了问题,尽管我不确定这是否是一个理想的解决方案,但仍然会标记为答案。