【问题标题】:Visual Studio's Test Explorer breaks when trying to link object files尝试链接目标文件时,Visual Studio 测试资源管理器中断
【发布时间】:2020-07-07 16:04:43
【问题描述】:

我想使用 Visual Studio 的测试资源管理器来运行我的 Google 测试。当我创建控制台项目并添加默认 Google 测试项目并构建解决方案时,它会按预期找到测试。

现在我想创建自己的类,其中所有内容都在头文件中设置。

class foo
{
    public:
        foo() : the_count(0) {}
        ~foo() = default;

        void count_plus() { the_count++; };
        int get_count() { return the_count; };

    private:
        int the_count;
};

然后我修改我的test.cpp 文件(Visual Studio 的 Google 测试项目创建的默认文件)以使用我的新类。

#include "pch.h"
#include <iostream>
#include "..\ConsoleApplication2\foo.h"

class tester : public testing::Test {

    public:
        foo bar;

        void SetUpTestSuite() {
            std::cout << "Setup..\n";
        }

        void TearDownTestSuite() {
            std::cout << "Teardown..\n";
        }
};

TEST_F(tester, TestFixture1)
{
    EXPECT_EQ(bar.get_count(), 0);

    bar.count_plus();

    EXPECT_EQ(bar.get_count(), 1);
}

构建此解决方案还会自动检测测试并成功运行它们。

现在变得有趣了...当我将 foo 的实现移动到 .cpp 文件时。

foo.h

class foo
{
    public:
        foo();
        ~foo() = default;

        void count_plus();
        int get_count();

    private:
        int the_count;
};

foo.cpp

#include "foo.h"

foo::foo()
{
    the_count = 0;
}

void
foo::count_plus()
{
    the_count++;
}

int
foo::get_count()
{
    return the_count;
}

然后我构建解决方案,我最初收到一个链接器错误,抱怨未解决的外部问题。

但是,如果我将测试项目的链接器设置更改为指向另一个项目,如下所示:

Properties -> Linker -> Input -> Additional Dependencies -> add $(SolutionDir)ConsoleApplication2\$(IntDir)*.obj

我从this 得到答案,我可以成功构建项目。

但是,在我完成项目构建后,我无法再查看或运行我的测试。

我在这里做错了吗?还是 Visual Studio 刚刚坏了?

【问题讨论】:

    标签: c++ visual-studio googletest


    【解决方案1】:

    我想通了。生成目标文件的项目不能有 main() 函数,因为这会覆盖 Google Test 的 main() 函数。

    我解决了:

    1. 创建一个 empty 项目(没有 main()),其中包含我所有的源代码,并将该项目的 Configuration Type 设置为 Static 库( .lib).

    2. 创建一个包含我的main() 入口点的控制台应用程序项目(或任何适合您需要的项目)。在这个项目中,我添加了对我的.lib 项目的引用。

    3. 创建一个 Google 测试项目。在这个项目中,我还添加了对我的.lib 项目的引用。

    4. 将第二步中的项目设置为启动项目

    现在,当您要运行代码时,它将从您的一个入口点运行它,但从 .lib 项目中获取源代码,您的 Google 测试项目也将获取此 .lib 文件,检测您的所有测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多