我是否必须将经过测试的源文件添加到 VS2017 中的单元测试项目?

Do I have to add tested source files to unit tests' project in VS2017?

我正在尝试使用 this 教程为我的项目编写单元测试。

编译包含测试的项目后,我收到链接器错误,几乎与 this question. The problem is that solution there was adding reference to a project being tested but I've already did it and I still get the same errors as if the reference wasn't added. Then I found 问题中的相同。解决方案就是将测试过的源文件添加到测试项目中,当然可以正常工作。

这是给我 error LNK2019: unresolved external symbol:

的示例代码

A.h(在.exe项目中)

#pragma once

struct A
{
    int a;

    A(int a);
};

A.cpp(在.exe项目中)

#include "A.h"

A::A(int a) : a(a)
{
}

Tests.cpp(在测试项目中)

#include "stdafx.h"
#include "CppUnitTest.h"
#include "../Example/A.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

TEST_CLASS(UnitTests)
{
public:
    TEST_METHOD(TestStructInitialization)
    {
        int a = 5;
        A testObject(a);
        Assert::AreEqual(a, testObject.a);
    }
};

也许我误解了什么,但我认为添加引用应该允许在不需要将源文件添加到测试项目的情况下进行测试。在我已经提到的 first tutorial 中,没有关于将源文件添加到测试项目的内容,但即使添加了引用,它对我也不起作用。将每个源文件添加到两个项目并不是测试所有内容的快速方法,所以我想知道是否有另一种方法。

当然,您的测试必须能够访问它需要的功能。由于一个可执行文件不能 link 反对另一个可执行文件,您有两个选择:

  • 在单元测试项目中也添加源文件
  • 重构代码,以便您要测试的代码是一个库(静态或共享),该库针对所有三个可执行文件进行 linked。