Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing classes from an VC++ .EXE project from a unit tests .EXE project

I've got an old legacy C++ app that I'm trying to write some unit tests for. I've created a second project in my solution that builds to a unit testing executable (using googletest). The test project references the header files from the main project. The test project builds fine until I try and use one of the classes from the main project.

#include "stdafx.h"

#include "JsContext.h"
#include "gtest/gtest.h"

TEST(JsContextTests, CreateJsContext) {
  JsContext context; // linking fails as soon as this line is added
}

Produces..

Error   1   error LNK2001: unresolved external symbol "public: __thiscall JsContext::JsContext(void)" (??0JsContext@@QAE@XZ)    JsContextTests.obj  tests
Error   2   fatal error LNK1120: 1 unresolved externals D:\Projects\Js-Clean\src\Debug\tests.exe    tests

The main executable doesn't produce a .lib file so I'm unsure what I should be linking the test project against.

What's the best approach to unit testing classes from another EXE project?

like image 710
chillitom Avatar asked Mar 28 '12 12:03

chillitom


1 Answers

If your main project doesn't produce a library, you need to link against the .obj file generated from JsContext.cpp, or whichever file has the source for JsContext.h. However, it should be trivial to change your main project to build into a static library, instead of executable. You can do this in the Project Properties, under Configuration -> General -> Configuration Type.

If building a static library isn't possible, I think your best choice would probably be to just recompile the source files in your test project; you could add a 'Main Project Dependencies' filter and only include the source files needed for what you're testing.

If that's not possible, as a last resort, you may be able to use a pre-link event to copy the relevant .obj files from the main project's output directory to your test project's output directory, but I wouldn't suggest this.

like image 67
Collin Dauphinee Avatar answered Nov 14 '22 02:11

Collin Dauphinee