Ava
Ava

Reputation: 838

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:

A.h (in .exe project)

#pragma once

struct A
{
    int a;

    A(int a);
};

A.cpp (in .exe project)

#include "A.h"

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

Tests.cpp (in tests project)

#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.

Upvotes: 1

Views: 341

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

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.

Upvotes: 2

Related Questions