使用外部依赖项运行 VC++ 单元测试时“无法设置执行上下文”

And*_*dry 4 c++ unit-testing visual-studio visual-c++

我有一个解决方案(在此链接上的 Git 上可用),包括一个项目(生成一个 DLL 库)和一个本机单元测试。

  • 带有 VC++ 的 Visual Studio Enterprise 2015
  • 在 Windows 10 上

我的解决方案的结构如下:

./src
+--DelaunayTriangulator.UnitTest
|  |--DelaunayTriangulatorTest.cpp
|  |--DelaunayTriangulator.UnitTest.vcxproj
+--DelaunayTriangulator
|  |--DelaunayTriangulator.cpp
|  |--DelaunayTriangulator.h
|  |--DelaunayTriangulator.vcxproj
|--Triangulator.sln
Run Code Online (Sandbox Code Playgroud)

该项目

我的源项目工作正常并且构建良好。它链接了一些库(AFAIK,它们基本上是静态库),这些库只是我需要作为依赖项的一些CGAL东西。它也运行良好。

如果您查看该项目,您会发现我将这些.lib文件链接为链接器选项的一部分:

<Link>
      <AdditionalDependencies>$(CGALDirPath)\build\lib\Debug\CGAL-vc140-mt-gd-4.12.lib;$(CGALDirPath)\auxiliary\gmp\lib\libgmp-10.lib;$(CGALDirPath)\auxiliary\gmp\lib\libmpfr-4.lib;..</AdditionalDependencies>
      ...
</Link>
Run Code Online (Sandbox Code Playgroud)

测试项目

单元测试项目是使用Visual Studio 中的本机测试项目演练和模板创建的。该测试项目也连接相同的.lib文件源项目一样。以下是我的单项测试:

#include "stdafx.h"
#include "CppUnitTest.h"

#include "../DelaunayTriangulator/DelaunayTriangulator.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace CodeAlive::Triangulation;

namespace TriangulatorUnitTest {
    TEST_CLASS(DelaunayTriangulatorTest) {

    public:
        TEST_METHOD(PerformTriangulation) {
            DelaunayTriangulator* triangulator = new DelaunayTriangulator();
            int result = triangulator->Perform();

            Assert::AreEqual<int>(0, result, L"Wrong result", LINE_INFO());

            delete triangulator;
        }
    }; // class
} // ns
Run Code Online (Sandbox Code Playgroud)

在我.lib从 CGAL链接这些文件之前,该项目确实构建了但根本没有运行,显示以下错误消息:

消息:无法设置执行上下文来运行测试

错误

一旦我添加了.lib文件,项目就会构建,并且只有当我不Assert注释该行时,单个单元测试才会运行(我必须注释引用我的源项目的所有代码):

TEST_CLASS(DelaunayTriangulatorTest) {
public:
    TEST_METHOD(PerformTriangulation) {
        Assert::AreEqual<int>(0, 0, L"Wrong result", LINE_INFO());
    }
};
Run Code Online (Sandbox Code Playgroud)

当我取消注释引用我的项目的代码(使用我在源项目中定义的类)时,当我尝试运行测试时会显示相同的错误消息:

TEST_CLASS(DelaunayTriangulatorTest) {
public:
    TEST_METHOD(PerformTriangulation) {
        DelaunayTriangulator* triangulator = new DelaunayTriangulator();
        int result = triangulator->Perform();

        Assert::AreEqual<int>(0, result, L"Wrong result", LINE_INFO());

        delete triangulator;
    }
};
Run Code Online (Sandbox Code Playgroud)

我知道这是由于外部引用的某种问题。这里有什么问题?

And*_*dry 10

所以这里的问题对我的配置有点特殊,但也足够通用,值得其他开发人员回答,他们可能会遇到这种情况。

问题是.dll我的源项目的s 没有部署到测试输出文件夹。所以你需要OutDir在你的测试项目属性中设置:

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
  <LinkIncremental>true</LinkIncremental>
  <OutDir>$(ProjectDir)$(Platform)\$(Configuration)\</OutDir>
</PropertyGroup>
Run Code Online (Sandbox Code Playgroud)

这将使测试实际复制 dll 不在解决方案文件夹中,而是在测试项目文件夹中,然后将正确复制引用的源项目 dll。测试项目文件没有 条目OutDir,这似乎使 MSBuild 无法复制源工件。