fake/mock nonvirtual C++ methods - c++

It known that in C++ mocking/faking nonvirtual methods for testing is hard. For example, cookbook of googlemock has two suggestion - both mean to modify original source code in some way (templating and rewriting as interface).
It appear this is very bad problem for C++ code. How can be done best if you can't modify original code that needs to be faked/mocked? Duplicating whole code/class (with it whole base class hierarchy??)

One way that we sometimes use is to split the original .cpp file into at least two parts.
Then the test apparatus can supply its own implementations; effectively using the linker to do the dirty work for us.
This is called the "Link Seam" in some circles.

I followed the Link Seam link from sdg's answer. There I read about different types of seams, but I was most impressed by Preprocessing Seams. This made me think about exploiting further the preprocessor. It turned out that it is possible to mock any external dependency without actually changing the calling code.
To do this, you have to compile the calling source file with a substitute dependency definition.
Here is an example how to do it.
dependency.h
#ifndef DEPENDENCY_H
#define DEPENDENCY_H
class Dependency
{
public:
//...
int foo();
//...
};
#endif // DEPENDENCY_H
caller.cpp
#include "dependency.h"
int bar(Dependency& dependency)
{
return dependency.foo() * 2;
}
test.cpp
#include <assert.h>
// block original definition
#define DEPENDENCY_H
// substitute definition
class Dependency
{
public:
int foo() { return 21; }
};
// include code under test
#include "caller.cpp"
// the test
void test_bar()
{
Dependency mockDependency;
int r = bar(mockDependency);
assert(r == 42);
}
Notice that the mock does not need to implement complete Dependency, just the minimum (used by caller.cpp) so the test can compile and execute.
This way you can mock non-virtual, static, global functions or almost any dependency without changing the productive code.
Another reason I like this approach is that everything related to the test is in one place. You don't have to tweak compiler and linker configurations here and there.
I have applied this technique successfully on a real world project with big fat dependencies.
I have described it in more detail in Include mock.

Code has to be written to be testable, by whatever test techniques you use. If you want to test using mocks, that means some form of dependency injection.
Non-virtual calls with no dependence on a template parameter pose the same problem as final and static methods in Java[*] - the code under test has explicitly said, "I want to call this code, not some unknown bit of code that's dependent in some way on an argument". You, the tester, want it to call different code under test from what it normally calls. If you can't change the code under test then you, the tester, will lose that argument. You might as well ask how to introduce a test version of line 4 of a 10-line function without changing the code under test.
If the class to be mocked is in a different TU from the class under test, you can write a mock with the same name as the original and link that instead. Whether you can generate that mock using your mocking framework in the normal way, I'm not so sure.
If you like, I suppose it's a "very bad problem for C++" that it's possible to write code that's hard to test. It shares this "problem" with a great number of other languages...
[*] My Java knowledge is quite low-power. There may be some clever way of mocking such methods in Java, which aren't applicable to C++. If so, please disregard them in order to see the analogy ;-)

I think it is not possible to do it with standard C++ right now (but lets hope that a powerful compile-time reflection will come to C++ soon...). However, there are a number of options for doing so.
You might have a look at Injector++. It is Windows only right now, but plans to add support for Linux & Mac.
Another option is CppFreeMock, which seems to work with GCC, but has no recent activities.
HippoMocks also provide such ability, but only for free functions. It doesn't support it for class member functions.
I'm not completely sure, but it seems that all the above achieve this with overwriting the target function at runtime so that it jumps to the faked function.
The there is C-Mock, which is an extension to Google Mock allowing you to mock non-virtual functions by redefining them, and relying on the fact that original functions are in dynamic libraries. It is limited to GNU/Linux platform.
Finally, you might also try PowerFake (for which, I'm the author) as introduced here.
It is not a mocking framework (currently) and it provides the possibility for replacing production functions with test ones. I hope to be able to integrate it to one or more mocking frameworks; if not, it'll become one.
Update: It has an integration with FakeIt.
Update 2: Added support for Google Mock
It also overrides the original function during linking (so, it won't work if a function is called in the same translation unit in which it is defined), but uses a different trick than C-Mock as it uses GNU ld's --wrap option. It also needs some changes to your build system for tests, but doesn't affect the main code in any way (except if you are forced to put a function in a separate .cpp file); but support for easily integrating it into CMake projects is provided.
But, it is currently limited to GCC/GNU ld (works also with MinGW).
Update: It supports GCC & Clang compilers, and GNU ld & LLVM lld linkers (or any compatible linker).

#zaharpopov you can use Typemock IsolatorPP to create mocks of non-virtual class and methods without changing your code (or legacy code).
for example if you have a non-virtual class called MyClass:
class MyClass
{
public:
int GetResult() { return -1; }
}
you can mock it with typemock like so:
MyClass* fakeMyClass = FAKE<MyClass>();
WHEN_CALLED(fakeMyClass->GetResult()).Return(10);
By the way the classes or methods that you want to test can also be private as typemock can mock them too, for example:
class MyClass
{
private:
int PrivateMethod() { return -1; }
}
MyClass* myClass = new MyClass();
PRIVATE_WHEN_CALLED(myClass, PrivateMethod).Return(1);
for more information go here.

You very specifically say "if you can't modify original code", which the techniques you mention in your question (and all the other current "answers") do.
Without changing that source, you can still generally (for common OSes/tools) preload an object that defines its own version of the function(s) you wish to intercept. They can even call the original functions afterwards. I provided an example of doing this in (my) question Good Linux TCP/IP monitoring tools that don't need root access?.

That is easier then you think. Just pass the constructed object to the constructor of the class you are testing. In the class store the reference to that object. Then it is easy to use mock classes.
EDIT :
The object that you are passing to the constructor needs an interface, and that class store just the reference to the interface.
struct Abase
{
virtual ~Abase(){}
virtual void foo() = 0;
};
struct Aimp : public Abase
{
virtual ~Aimp(){}
virtual void foo(){/*do stuff*/}
};
struct B
{
B( Aimp &objA ) : obja( objA )
{
}
void boo()
{
objA.foo();
}
Aimp &obja;
};
int main()
{
//...
Aimp realObjA;
B objB( realObjA );
// ...
}
In the test, you can pass the mock object easy.

I used to create an interface for the parts I needed to mock. Then I simply created a stub class that derived from this interface and passed this instance to my classes under test. Yes, it is a lot of hard work, but I found it worth it for some circumstances.
Oh, by interface I mean a struct with only pure virtual methods. Nothing else!

Related

How to do stubbing or Mock memset and memcpy unction in GTest? [duplicate]

I am stuck in a problem and can't seem to find the solution.
I am using VS2005 SP1 for compiling the code.
I have a global function:
A* foo();
I have a mock class
class MockA : public A {
public:
MOCK_METHOD0 (bar, bool());
...
};
In the sources, it is accessed like this: foo()->bar(). I cannot find a way to mock this behavior. And I cannot change the sources, so the solution in google mock cook book is out of question.
Any help or pointers in the right direction will be highly appreciated. :)
No it's not possible, without changing the sources, or bringing your own version of foo() that is linked with the executable code.
From GoogleMock's FAQ it says
My code calls a static/global function. Can I mock it?
You can, but you need to make some changes.
In general, if you find yourself needing to mock a static function, it's a sign that your modules are too tightly coupled (and less flexible, less reusable, less testable, etc). You are probably better off defining a small interface and call the function through that interface, which then can be easily mocked. It's a bit of work initially, but usually pays for itself quickly.
This Google Testing Blog post says it excellently. Check it out.
Also from the Cookbook
Mocking Free Functions
It's possible to use Google Mock to mock a free function (i.e. a C-style function or a static method). You just need to rewrite your code to use an interface (abstract class).
Instead of calling a free function (say, OpenFile) directly, introduce an interface for it and have a concrete subclass that calls the free function:
class FileInterface {
public:
...
virtual bool Open(const char* path, const char* mode) = 0;
};
class File : public FileInterface {
public:
...
virtual bool Open(const char* path, const char* mode) {
return OpenFile(path, mode);
}
};
Your code should talk to FileInterface to open a file. Now it's easy to mock out the function.
This may seem much hassle, but in practice you often have multiple related functions that you can put in the same interface, so the per-function syntactic overhead will be much lower.
If you are concerned about the performance overhead incurred by virtual functions, and profiling confirms your concern, you can combine this with the recipe for mocking non-virtual methods.
As you mentioned in your comment that you actually provide your own version of foo(), you can easily solve this having a global instance of another mock class:
struct IFoo {
virtual A* foo() = 0;
virtual ~IFoo() {}
};
struct FooMock : public IFoo {
FooMock() {}
virtual ~FooMock() {}
MOCK_METHOD0(foo, A*());
};
FooMock fooMock;
// Your foo() implementation
A* foo() {
return fooMock.foo();
}
TEST(...) {
EXPECT_CALL(fooMock,foo())
.Times(1)
.WillOnceReturn(new MockA());
// ...
}
Don't forget to clear all call expectations, after each test case run.
There are 2 options:
If you insist on using gmock, there's an "extension" for global mocking from apriorit: https://github.com/apriorit/gmock-global
It's rather limited, though - or at least I couldn't figure out in 5 minutes how to have side effects on a mocked call.
If you're willing to switch from gmock, then hippomocks has a very neat way of doing what you want.
Here's an example for mocking fopen, fclose and fgets for testing a member function which reads from a file using cstdio (streams are very inefficient):
TEST_CASE("Multi entry") {
std::vector<std::string> files{"Hello.mp3", "World.mp3"};
size_t entry_idx = 0;
MockRepository mocks;
mocks.OnCallFunc(fopen).Return(reinterpret_cast<FILE *>(1));
mocks.OnCallFunc(fgets).Do(
[&](char * buf, int n, FILE * f)->char *{
if (entry_idx < files.size())
{
strcpy(buf, files[entry_idx++].c_str());
return buf;
}
else
return 0;
}
);
mocks.OnCallFunc(fclose).Return(0);
FileExplorer file_explorer;
for (const auto &entry: files)
REQUIRE_THAT(file_explorer.next_file_name(), Equals(entry.c_str()));
REQUIRE_THAT(file_explorer.next_file_name(), Equals(""));
}
Where the function under test looks like this:
string FileExplorer::next_file_name() {
char entry[255];
if (fgets((char *)entry, 255, _sorted_entries_in_dir) == NULL)
return string();
_current_idx++;
if (_current_idx == _line_offsets.size())
_line_offsets.push_back(static_cast<unsigned>(char_traits<char>::length(entry)) + _line_offsets.back());
return string(entry);
}
I'm using catch2 as the testing framework here, but I think hippomocks would work with Google's Testing framework as well (I recommend catch2, by the way, really easy to work with).
Of course, the answer explaining the solution according to GTest/GMock's documentation couldn't be much more correct.
But I would like to add a temporary quick&dirty approach. It should be applicable to cases where you want to get legacy C/C++ code under test as quickly and as non-invasively as possible. (Just to proceed with fixes, refactoring and more proper testing as soon as possible after.)
So, to mock a free function void foo(int) appearing in some code to be tested, within the source file you just make the following adaptions:
#if TESTING
#define foo(param) // to nothing, so calls to that disappear
#endif
// ... code that calls foo stays untouched and could be tested
The macro TESTING, indicating that the code runs under test, doesn't come with GTest/GMock - you need to add it to test targets by yourself.
The possibilities are rather limited, but you might also be able to construct something useful for return types as A* in the question's example.
Unfortunately, also this isn't a solution without changing the code.
If that is really necessary, you could Google for 'link seams'. But my guess is that this could be quite a hassle in practice. And it even might not be possible at all in many/most cases?!
If your free function is in the form of an std::function object, you can mock it using MockFunction. See this answer
What has worked for me is
to define A* foo() in a separate source file foo.cpp in the main project,
not to include foo.cpp in the test project,
include a different source file mock-foo.cpp in the test project that provides the mock implementation of A* foo().
For example, pseudocode for the main project file (e.g. .vcxproj or CMakeLists.txt):
include src/foo.hpp # declare A* foo()
include src/foo.cpp # define A* foo()
and the test project file:
include src/foo.hpp
include test/mock-foo.cpp # define mocked A* foo()
Simple and sweet, but may or may not work in your case.

How to mock std::localtime in cpp [duplicate]

I am stuck in a problem and can't seem to find the solution.
I am using VS2005 SP1 for compiling the code.
I have a global function:
A* foo();
I have a mock class
class MockA : public A {
public:
MOCK_METHOD0 (bar, bool());
...
};
In the sources, it is accessed like this: foo()->bar(). I cannot find a way to mock this behavior. And I cannot change the sources, so the solution in google mock cook book is out of question.
Any help or pointers in the right direction will be highly appreciated. :)
No it's not possible, without changing the sources, or bringing your own version of foo() that is linked with the executable code.
From GoogleMock's FAQ it says
My code calls a static/global function. Can I mock it?
You can, but you need to make some changes.
In general, if you find yourself needing to mock a static function, it's a sign that your modules are too tightly coupled (and less flexible, less reusable, less testable, etc). You are probably better off defining a small interface and call the function through that interface, which then can be easily mocked. It's a bit of work initially, but usually pays for itself quickly.
This Google Testing Blog post says it excellently. Check it out.
Also from the Cookbook
Mocking Free Functions
It's possible to use Google Mock to mock a free function (i.e. a C-style function or a static method). You just need to rewrite your code to use an interface (abstract class).
Instead of calling a free function (say, OpenFile) directly, introduce an interface for it and have a concrete subclass that calls the free function:
class FileInterface {
public:
...
virtual bool Open(const char* path, const char* mode) = 0;
};
class File : public FileInterface {
public:
...
virtual bool Open(const char* path, const char* mode) {
return OpenFile(path, mode);
}
};
Your code should talk to FileInterface to open a file. Now it's easy to mock out the function.
This may seem much hassle, but in practice you often have multiple related functions that you can put in the same interface, so the per-function syntactic overhead will be much lower.
If you are concerned about the performance overhead incurred by virtual functions, and profiling confirms your concern, you can combine this with the recipe for mocking non-virtual methods.
As you mentioned in your comment that you actually provide your own version of foo(), you can easily solve this having a global instance of another mock class:
struct IFoo {
virtual A* foo() = 0;
virtual ~IFoo() {}
};
struct FooMock : public IFoo {
FooMock() {}
virtual ~FooMock() {}
MOCK_METHOD0(foo, A*());
};
FooMock fooMock;
// Your foo() implementation
A* foo() {
return fooMock.foo();
}
TEST(...) {
EXPECT_CALL(fooMock,foo())
.Times(1)
.WillOnceReturn(new MockA());
// ...
}
Don't forget to clear all call expectations, after each test case run.
There are 2 options:
If you insist on using gmock, there's an "extension" for global mocking from apriorit: https://github.com/apriorit/gmock-global
It's rather limited, though - or at least I couldn't figure out in 5 minutes how to have side effects on a mocked call.
If you're willing to switch from gmock, then hippomocks has a very neat way of doing what you want.
Here's an example for mocking fopen, fclose and fgets for testing a member function which reads from a file using cstdio (streams are very inefficient):
TEST_CASE("Multi entry") {
std::vector<std::string> files{"Hello.mp3", "World.mp3"};
size_t entry_idx = 0;
MockRepository mocks;
mocks.OnCallFunc(fopen).Return(reinterpret_cast<FILE *>(1));
mocks.OnCallFunc(fgets).Do(
[&](char * buf, int n, FILE * f)->char *{
if (entry_idx < files.size())
{
strcpy(buf, files[entry_idx++].c_str());
return buf;
}
else
return 0;
}
);
mocks.OnCallFunc(fclose).Return(0);
FileExplorer file_explorer;
for (const auto &entry: files)
REQUIRE_THAT(file_explorer.next_file_name(), Equals(entry.c_str()));
REQUIRE_THAT(file_explorer.next_file_name(), Equals(""));
}
Where the function under test looks like this:
string FileExplorer::next_file_name() {
char entry[255];
if (fgets((char *)entry, 255, _sorted_entries_in_dir) == NULL)
return string();
_current_idx++;
if (_current_idx == _line_offsets.size())
_line_offsets.push_back(static_cast<unsigned>(char_traits<char>::length(entry)) + _line_offsets.back());
return string(entry);
}
I'm using catch2 as the testing framework here, but I think hippomocks would work with Google's Testing framework as well (I recommend catch2, by the way, really easy to work with).
Of course, the answer explaining the solution according to GTest/GMock's documentation couldn't be much more correct.
But I would like to add a temporary quick&dirty approach. It should be applicable to cases where you want to get legacy C/C++ code under test as quickly and as non-invasively as possible. (Just to proceed with fixes, refactoring and more proper testing as soon as possible after.)
So, to mock a free function void foo(int) appearing in some code to be tested, within the source file you just make the following adaptions:
#if TESTING
#define foo(param) // to nothing, so calls to that disappear
#endif
// ... code that calls foo stays untouched and could be tested
The macro TESTING, indicating that the code runs under test, doesn't come with GTest/GMock - you need to add it to test targets by yourself.
The possibilities are rather limited, but you might also be able to construct something useful for return types as A* in the question's example.
Unfortunately, also this isn't a solution without changing the code.
If that is really necessary, you could Google for 'link seams'. But my guess is that this could be quite a hassle in practice. And it even might not be possible at all in many/most cases?!
If your free function is in the form of an std::function object, you can mock it using MockFunction. See this answer
What has worked for me is
to define A* foo() in a separate source file foo.cpp in the main project,
not to include foo.cpp in the test project,
include a different source file mock-foo.cpp in the test project that provides the mock implementation of A* foo().
For example, pseudocode for the main project file (e.g. .vcxproj or CMakeLists.txt):
include src/foo.hpp # declare A* foo()
include src/foo.cpp # define A* foo()
and the test project file:
include src/foo.hpp
include test/mock-foo.cpp # define mocked A* foo()
Simple and sweet, but may or may not work in your case.

Is the C++ linker smart about virtual methods used only from one class in a program?

I work on a project with extremely low unit test culture. We have almost zero unit testing and every API is static.
To be able to unit test some of my code I create wrappers like
class ApiWrapper {
virtual int Call(foo, bar) {
return ApiCall(foo, bar);
}
};
Now in my functions instead:
int myfunc() {
APiCall(foo, bar);
}
I do:
int myfunc(ApiWrapper* wrapper) {
wrapper->Call(foo, bar);
}
This way I am able to mock such functionality. The problem is that some colleagues complain that production code should not be affected from testability needs - nonsense I know, but reality.
Anyway, I believe that I read somewhere at some point that compilers are actually smart about replacing unused polymorphic behavior with a direct call ... or if there is no class that overrides a virtual method it becomes "normal".
I experimented, and on gcc 4.8 it does not inline or directly call the virtual method, but instead creates vt.
I tried to google, but I did not find anything about this. Is this a thing or do I misremember ... or I have to do something to explain this to the linker, an optimization flag or something?
Note that while in production this class is final, in the test environment it is not. This is exactly what the linker has to be smart about and detect it.
The C++ compiler will only replace a polymorphic call with a direct call if it knows for certain what the actual type is.
So in the following snippet, it will be optimized:
void f() {
ApiWrapper x;
x.Call(); // Can be replaced
}
But in the general case, it can't:
void f(ApiWrapper* wrapper) {
wrapper->Call(); // Cannot be replaced
}
You also added two conditions to your question:
if there is no class that overrides a virtual method it becomes "normal".
This will not help. Neither the C++ compiler nor the linker will look at the totality of classes to search whether any inheritor exists. It's futile anyway, since you can always dynamically-load an instance of a new class.
By the way, this optimization is indeed performed by some JVMs (called devirtualization) - since in Java land there's a class loader which is aware of which classes are currently loaded.
in production this class is final
That will help! Clang, for example, will convert virtual calls to non-virtual calls if the method / method's class is marked final.

Mocking free function

I am stuck in a problem and can't seem to find the solution.
I am using VS2005 SP1 for compiling the code.
I have a global function:
A* foo();
I have a mock class
class MockA : public A {
public:
MOCK_METHOD0 (bar, bool());
...
};
In the sources, it is accessed like this: foo()->bar(). I cannot find a way to mock this behavior. And I cannot change the sources, so the solution in google mock cook book is out of question.
Any help or pointers in the right direction will be highly appreciated. :)
No it's not possible, without changing the sources, or bringing your own version of foo() that is linked with the executable code.
From GoogleMock's FAQ it says
My code calls a static/global function. Can I mock it?
You can, but you need to make some changes.
In general, if you find yourself needing to mock a static function, it's a sign that your modules are too tightly coupled (and less flexible, less reusable, less testable, etc). You are probably better off defining a small interface and call the function through that interface, which then can be easily mocked. It's a bit of work initially, but usually pays for itself quickly.
This Google Testing Blog post says it excellently. Check it out.
Also from the Cookbook
Mocking Free Functions
It's possible to use Google Mock to mock a free function (i.e. a C-style function or a static method). You just need to rewrite your code to use an interface (abstract class).
Instead of calling a free function (say, OpenFile) directly, introduce an interface for it and have a concrete subclass that calls the free function:
class FileInterface {
public:
...
virtual bool Open(const char* path, const char* mode) = 0;
};
class File : public FileInterface {
public:
...
virtual bool Open(const char* path, const char* mode) {
return OpenFile(path, mode);
}
};
Your code should talk to FileInterface to open a file. Now it's easy to mock out the function.
This may seem much hassle, but in practice you often have multiple related functions that you can put in the same interface, so the per-function syntactic overhead will be much lower.
If you are concerned about the performance overhead incurred by virtual functions, and profiling confirms your concern, you can combine this with the recipe for mocking non-virtual methods.
As you mentioned in your comment that you actually provide your own version of foo(), you can easily solve this having a global instance of another mock class:
struct IFoo {
virtual A* foo() = 0;
virtual ~IFoo() {}
};
struct FooMock : public IFoo {
FooMock() {}
virtual ~FooMock() {}
MOCK_METHOD0(foo, A*());
};
FooMock fooMock;
// Your foo() implementation
A* foo() {
return fooMock.foo();
}
TEST(...) {
EXPECT_CALL(fooMock,foo())
.Times(1)
.WillOnceReturn(new MockA());
// ...
}
Don't forget to clear all call expectations, after each test case run.
There are 2 options:
If you insist on using gmock, there's an "extension" for global mocking from apriorit: https://github.com/apriorit/gmock-global
It's rather limited, though - or at least I couldn't figure out in 5 minutes how to have side effects on a mocked call.
If you're willing to switch from gmock, then hippomocks has a very neat way of doing what you want.
Here's an example for mocking fopen, fclose and fgets for testing a member function which reads from a file using cstdio (streams are very inefficient):
TEST_CASE("Multi entry") {
std::vector<std::string> files{"Hello.mp3", "World.mp3"};
size_t entry_idx = 0;
MockRepository mocks;
mocks.OnCallFunc(fopen).Return(reinterpret_cast<FILE *>(1));
mocks.OnCallFunc(fgets).Do(
[&](char * buf, int n, FILE * f)->char *{
if (entry_idx < files.size())
{
strcpy(buf, files[entry_idx++].c_str());
return buf;
}
else
return 0;
}
);
mocks.OnCallFunc(fclose).Return(0);
FileExplorer file_explorer;
for (const auto &entry: files)
REQUIRE_THAT(file_explorer.next_file_name(), Equals(entry.c_str()));
REQUIRE_THAT(file_explorer.next_file_name(), Equals(""));
}
Where the function under test looks like this:
string FileExplorer::next_file_name() {
char entry[255];
if (fgets((char *)entry, 255, _sorted_entries_in_dir) == NULL)
return string();
_current_idx++;
if (_current_idx == _line_offsets.size())
_line_offsets.push_back(static_cast<unsigned>(char_traits<char>::length(entry)) + _line_offsets.back());
return string(entry);
}
I'm using catch2 as the testing framework here, but I think hippomocks would work with Google's Testing framework as well (I recommend catch2, by the way, really easy to work with).
Of course, the answer explaining the solution according to GTest/GMock's documentation couldn't be much more correct.
But I would like to add a temporary quick&dirty approach. It should be applicable to cases where you want to get legacy C/C++ code under test as quickly and as non-invasively as possible. (Just to proceed with fixes, refactoring and more proper testing as soon as possible after.)
So, to mock a free function void foo(int) appearing in some code to be tested, within the source file you just make the following adaptions:
#if TESTING
#define foo(param) // to nothing, so calls to that disappear
#endif
// ... code that calls foo stays untouched and could be tested
The macro TESTING, indicating that the code runs under test, doesn't come with GTest/GMock - you need to add it to test targets by yourself.
The possibilities are rather limited, but you might also be able to construct something useful for return types as A* in the question's example.
Unfortunately, also this isn't a solution without changing the code.
If that is really necessary, you could Google for 'link seams'. But my guess is that this could be quite a hassle in practice. And it even might not be possible at all in many/most cases?!
If your free function is in the form of an std::function object, you can mock it using MockFunction. See this answer
What has worked for me is
to define A* foo() in a separate source file foo.cpp in the main project,
not to include foo.cpp in the test project,
include a different source file mock-foo.cpp in the test project that provides the mock implementation of A* foo().
For example, pseudocode for the main project file (e.g. .vcxproj or CMakeLists.txt):
include src/foo.hpp # declare A* foo()
include src/foo.cpp # define A* foo()
and the test project file:
include src/foo.hpp
include test/mock-foo.cpp # define mocked A* foo()
Simple and sweet, but may or may not work in your case.

How Do You Create Test Objects For Third Party Legacy Code

I have a code base where many of the classes I implement derive from classes that are provided by other divisions of my company. Working with these other devisions often have the working relationship as though they are third party middle ware vendors.
I'm trying to write test code without modifying these base classes. However, there are issues with creating meaningful test
objects due to the lack of interfaces:
//ACommonClass.h
#include "globalthermonuclearwar.h" //which contains deep #include dependencies...
#include "tictactoe.h" //...and need to exist at compile time to get into test...
class Something //which may or may not inherit from another class similar to this...
{
public:
virtual void fxn1(void); //which often calls into many other classes, similar to this
//...
int data1; //will be the only thing I can test against, but is often meaningless without fxn1 implemented
//...
};
I'd normally extract an interface and work from there, but as these are "Third Party", I can't commit these changes.
Currently, I've created a separate file that holds fake implementations for functions that are defined in the third-party supplied base class headers on a need to know basis, as has been described in the book "Working with Legacy Code".
My plan was to continue to use these definitions and provide alternative test implementations for each third party class that I needed:
//SomethingRequiredImplementations.cpp
#include "ACommonClass.h"
void CGlobalThermoNuclearWar::Simulate(void) {}; // fake this and all other required functions...
// fake implementations for otherwise undefined functions in globalthermonuclearwar.h's #include files...
void Something::fxn1(void) { data1 = blah(); } //test specific functionality.
But before I start doing that I was wondering if any one has tried providing actual objects on a code base similar to mine, which would allow creating new test specific classes to use in place of actual third-party classes.
Note all code bases in question are written in C++.
Mock objects are suitable for this kind of task. They allow you to simulate the existence of other components without needing them to be present. You simply define the expected input and output in your tests.
Google have a good mocking framework for C++.
I'm running into a very similar problem at the moment. I don't want to add a bunch of interfaces that are only there for the purpose of testing, so I can't use any of the existing mock object libraries. To get around this I do the same thing, creating a different file with fake implementations, and having my tests link the fake behaviour, and production code links the real behaviour.
What I wish I could do at this point, is take the internals of another mock framework, and use it inside my fake objects. It would look a little something like this:
Production.h
class ConcreteProductionClass { // regular everyday class
protected:
ConcreteProductionClass(); // I've found the 0 arg constructor useful
public:
void regularFunction(); // regular function that I want to mock
}
Mock.h
class MockProductionClass
: public ConcreteProductionClass
, public ClassThatLetsMeSetExpectations
{
friend class ConcreteProductionClass;
MockTypes membersNeededToSetExpectations;
public:
MockClass() : ConcreteProductionClass() {}
}
ConcreteProductionClass::regularFunction() {
membersNeededToSetExpectations.PassOrFailTheTest();
}
ProductionCode.cpp
void doSomething(ConcreteProductionClass c) {
c.regularFunction();
}
Test.cpp
TEST(myTest) {
MockProductionClass m;
m.SetExpectationsAndReturnValues();
doSomething(m);
ASSERT(m.verify());
}
The most painful part of all this is that the other mock frameworks are so close to this, but don't do it exactly, and the macros are so convoluted that it's not trivial to adapt them. I've begun looking into this on my spare time, but it's not moving along very quickly. Even if I got my method working the way I want, and had the expectation setting code in place, this method still has a couple drawbacks, one of them being that your build commands can get to be kind of long if you have to link against a lot of .o files rather than one .a, but that's manageable. It's also impossible to fall through to the default implementation, since we're not linking it. Anyway, I know this doesn't answer the question, or really even tell you anything you don't already know, but it shows how close the C++ community is to being able to mock classes that don't have a pure virtual interface.
You might want to consider mocking instead of faking as a potential solution. In some cases you may need to write wrapper classes that are mockable if the original classes aren't. I've done this with framework classes in C#/.Net, but not C++ so YMMV.
If I have a class that I need under test that derives from something I can't (or don't want to) run under test I'll:
Make a new logic-only class.
Move the code-i-wanna-test to the logic class.
Use an interface to talk back to the real class to interact with the base class and/or things I can't or won't put in the logic.
Define a test class using that same interface. This test class could have nothing but noops or fancy code that simulates the real classes.
If I have a class that I just need to use in testing, but using the real class is a problem (dependencies or unwanted behaviors):
I'll define a new interface that looks like all of the public methods I need to call.
I'll create a mock version of the object that supports that interface for testing.
I'll create another class that is constructed with a "real" version of that class. It also supports that interface. All interface calls a forwarded to the real object methods.
I'll only do this for methods I actually call - not ALL the public methods. I'll add to these classes as I write more tests.
For example, I wrap MFC's GDI classes like this to test Windows GDI drawing code. Templates can make some of this easier - but we often end up not doing that for various technical reasons (stuff with Windows DLL class exporting...).
I'm sure all this is in Feather's Working with Legacy Code book - and what I'm describing has actual terms. Just don't make me pull the book off the shelf...
One thing you did not indicate in your question is the reason why your classes derive from base classes from the other division. Is the relationship really a IS-A relationshiop ?
Unless your classes needs to be used by a framework, you could consider favoring delegation over inheritance. Then you can use dependency injection to provide your class with a mock of their class in the unit tests.
Otherwise, an idea would be to write a script to extract and create the interface your need from the header they provide, and integrate this to the compilation process so your unit test can ve checked in.