简体   繁体   English

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

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

I'm trying to write unit tests for my project using this tutorial.我正在尝试使用教程为我的项目编写单元测试。

After compiling project containing tests I get linker errors, almost the same ones as in 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 this question.然后我发现了这个问题。 Solution there is just adding tested source files to tests' project and of course it works fine.解决方案只是将经过测试的源文件添加到测试项目中,当然它工作正常。

Here is example code that gives me error LNK2019: unresolved external symbol :这是给我error LNK2019: unresolved external symbol示例代码:

Ah (in .exe project)啊(在 .exe 项目中)

#pragma once

struct A
{
    int a;

    A(int a);
};

A.cpp (in .exe project) A.cpp(在 .exe 项目中)

#include "A.h"

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

Tests.cpp (in tests project) 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);
    }
};

Maybe I misunderstood something but I think adding reference is a thing that should allow doing tests without the need to add source files to tests project.也许我误解了一些东西,但我认为添加引用应该允许在不需要将源文件添加到测试项目的情况下进行测试。 In the first tutorial , that I already mentioned, there is nothing about adding source files to tests project but it doesn't work for me even with reference added.在我已经提到的第一个教程中,没有关于将源文件添加到测试项目的任何内容,但即使添加了参考,它对我也不起作用。 Adding every source file to both projects isn't very fast way to test everything so I wonder if there's another way of doing it.将每个源文件添加到两个项目中并不是测试所有内容的快速方法,所以我想知道是否还有其他方法可以做到这一点。

Of course, your tests must have access to the functionality it needs.当然,您的测试必须能够访问它所需的功能。 And as an executable cannot link against another executable, you have two options:由于一个可执行文件无法链接到另一个可执行文件,您有两个选择:

  • Add the source files as well in the unit test project在单元测试项目中也添加源文件
  • Refactor the code so that the code you want to test is a library (static or shared) that gets linked against all three executables.重构代码,以便您要测试的代码是一个与所有三个可执行文件链接的库(静态或共享)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM