I've been racking my brain trying to think of the best way to access a protected member function from some test code in C++, here's my problem:
//in Foo.h
Class Foo
{
protected:
void DoSomething(Data data);
}
//in Blah.h
Class Blah
{
public:
Foo foo;
Data data;
};
//in test code...
Blah blah;
blah.foo.DoSomething(blah.data); // Here's my problem!
Some possible solutions so far:
Make the test code class a friend of Foo, but this pollutes Foo with test code
Make DoSomething a public function
I've looked at creating a test wrapper for Foo, as suggested in this post, however this won't work as Blah contains the instance of Foo.
All advice/insight/opinions are most welcome!
Thanks
There is a way which is completely allowed by the Standard.
//in Foo.h
class Foo
{
protected:
void DoSomething(Data data);
};
//in Blah.h
class Blah
{
public:
Foo foo;
Data data;
};
//in test code...
struct FooExposer : Foo {
using Foo::DoSomething;
};
Blah blah;
(blah.foo.*&FooExposer::DoSomething)(blah.data);
Read the Hidden features of C++ entry for an explanation.
You may write a macro for your convenience (the parenthesis are there so that you can use this macro also for types that have a comma, like vector<pair<A, B>>):
#define ACCESS(A, M, N) struct N : get_a1<void A>::type { using get_a1<void A>::type::M; }
template<typename T> struct get_a1;
template<typename R, typename A1> struct get_a1<R(A1)> { typedef A1 type; };
The matter now becomes
ACCESS((Foo), DoSomething, GetDoSomething);
Blah blah;
(blah.foo.*&GetDoSomething::DoSomething)(blah.data);
Ok, since you said it is only a test code I am going to suggest something seriously hacky but would work:
struct tc : protected Foo
{
tc(Foo *foo, Data& data)
{
((tc*)foo)->DoSomething(data);
}
};
Blah blah;
tc t(&blah.foo, blah.data);
On the one hand, don't do that.
On the other hand, here's a gamble:
#define protected public
#include "foo.h"
#undef protected
8-)
But seriously, why is DoSomething() protected? Probably because calling it from external code can break something. In which case, you shouldn't be calling it from your tests.
I've done
class Foo
{
protected:
void DoSomething(Data data);
public:
#ifdef TEST
void testDoSomething(Data data);
#endif
}
Then compile your unit tests with g++ -D TEST.
Rather than ifdefing private to public, consider ifdefing friendship, or better yet think if that function really needs to belong to that class, maybe it would suffice to have something in a named/unnamed namespace in a cpp, and then declared in a test project.
Anyway, check this link, maybe your testing framework would provide similar functionality.
EDIT: Did you consider inheriting your test class from your real class?
You could use inheritance with forwarding functions:
class Foo
{
protected:
void DoSomething(Data data);
}
class test_Foo : public Foo
{
public:
void testDoSomething(Data data)
{
DoSomething(data);
}
}
Use wrapper as follows:
// Foo.h unchanged
// Blah.h unchanged
// test code
class FooTest : public Foo { friend void test(); }; // make friends
void test()
{
Blah blah;
static_cast<FooTest*>(&blah.foo)->DoSomething(blah.data); // Here's no problem!
}
If it is strictly test code, you could do...
#define protected public
#include "Foo.h"
// test code
#undef protected
Related
I want to test some code that is written to run on an embedded processor in a Visual Studio Native Unit Test project.
The TestMe class has several methods that are good candidates for testing, but the Foo and Bar classes directly access memory mapped registers that are only available on the embedded processor.
#pragma once
#include "Foo.h"
#include "Bar.h"
class TestMe
{
public:
TestMe(Foo& aFoo, Bar& aBar);
~TestMe();
float FooBar();
};
What is the best way to mock away these objects so that I can test the TestMe class?
Edit: For me the best way would be the one that interferes as little as possible with the software that is being tested.
"Best" is always subjective, but I like using templates for this kind of mocking:
template <typename TFoo, typename TBar>
class TestMeImpl
{
public:
TestMeImpl(TFoo& aFoo, TBar& aBar);
~TestMeImpl();
float FooBar();
};
using TestMe = TestMeImpl<Foo, Bar>;
You would write unit tests against TestMeImpl, but expose TestMe to your users.
Your Foo and Bar are passed to constructor by reference.
There are two approaches to this.
My personal favor is to use interface and leverage polymorphic objects.
So it looks like this:
class IFoo {
public:
virtual void someFunction() = 0;
};
class IBar {
public:
virtual void otherFunction() = 0;
};
class Foo : public IFoo {
....
void someFunction() {
}
};
class Bar : public IBar {
.....
void otherFunction() {
}
};
class TestMe {
public:
TestMe(IFoo& aFoo, IBar& aBar);
~TestMe();
float FooBar();
};
// test code (GMock example):
class MockFoo : public IFoo {
MOCK_METHOD(someFunction(), void());
};
class MockBar : public IBar {
MOCK_METHOD(otherFunction(), void());
};
TEST(TestMeTest, someTest)
{
MockBar bar;
MockFoo foo;
TestMe testMe(bar, foo);
EXPECT_CALL(bar, otherFunction());
EXPECT_EQ(0.2, testMe.FooBar());
}
This is basically same thing as use of templates. In this case dynamic polymorphism is used.
In case of template you got something similar so some people call it static polymorphism.
Both approaches have pros and cons and it is your decision which one is best in your case.
There is a solution to not introduce interfaces only for testing purposes (:
Link time substitution.
Rules:
Foo and Bar are in a static lib (there can be separate libs for Foo and Bar)
Don't link these libs to test exec.
Create a mock implementation that will be linked to test exec:
Hpp file:
#pragma once
#include <gmock/gmock.h>
class FooMock
{
FooMock();
~FooMock();
MOCK_METHOD0(foo, void());
};
Cpp file:
#include "Foo.hpp"
#include "FooMock.hpp"
namespace
{
FooMock* fooMock;
}
FooMock::FooMock()
{
assert(!fooMock);
fooMock = this;
}
FooMock::~FooMock()
{
fooMock = nullptr;
}
// Implement real Foo::foo
void Foo::foo()
{
// call FooMock::foo
fooMock->foo();
}
Disadvantage is that it won't work for multithread tests.
Hope it helps.
Depending on the size and performance constraints of the embedded platform introducing interfaces for the sole purpose of unit testing can be a bad idea. For small systems I favor the approach of type-aliasing classes which represent some kind of processor peripheral. I guess that's also what "Foo" and "Bar" in your example represent.
The right type alias for the current target can be chosen by using architecture predefines
struct Uart1 {};
struct Uart1Mock {};
#ifdef __x86_64__
using SensorUart = Uart1Mock;
#else
using SensorUart = Uart1;
#endif
The application code then simply uses SensorUart, no matter if the class depends on an actual serial port or simply uses standard io.
The syntax of MOCK_METHOD can be used inside a class definition:
class A {
MOCK_METHOD0(f, void(void));
};
Is it possible to mock a method that has already been declared? What I want is to do something similar to:
#include "gmock/gmock.h"
class HelloTest {
void f();
};
MOCK_METHOD0(HelloTest::f, void(void));
The idea is to put the class definition in an hpp file and then the mocks in a cpp file. In effect, my class definition with its methods' prototypes needs to be in common with other cpp files in my build chain and I don't want to use virtual functions.
Unfortunately, when I try to do what I wrote above, I get the following error on the line that contains MOCK_METHOD0:
error: ‘gmock0_HelloTest’ has not been declared
What does this error mean and is there a way to do what I want?
To begin with, your MOCK_METHOD0() declaration must belong to a mock class, under a public section. For instance, your code snippet:
#include "gmock/gmock.h"
class HelloTest {
void f();
};
MOCK_METHOD0(HelloTest::f, void(void));
Should instead look like this:
#include "gmock/gmock.h"
class HelloTest {
virtual void f();
};
class Mock_HelloTest : public HelloTest {
public:
MOCK_METHOD0(f, void(void));
};
Now, you'll notice that I've changed f() to be virtual instead, since your use of HelloTest::f in MOCK_METHOD0 requires f() to be virtual.
Since you don't want to use virtual functions, your only other option is to use what the Google Mock team calls hi-perf dependency injection. With this non-virtual approach, you'd have to create a separate mock class that doesn't inherit from HelloTest. You'd also need to templatize any code that currently uses HelloTest to switch between HelloTest in production and Mock_HelloTest in tests.
As an example, let's say you have the following function that calls HelloTest::f():
void RunHelloTest() {
HelloTest HT;
HT.f();
}
You would set up your code snippet as follows:
#include "gmock/gmock.h"
class HelloTest {
void f(); // <- f is no longer virtual
};
class Mock_HelloTest { // <- Mock_HelloTest no longer inherits from HelloTest
public:
MOCK_METHOD0(f, void(void));
};
And modify RunHelloTest() to accept a template type argument:
template <class HelloTestClass>
void RunHelloTest() {
HelloTestClass HT;
HT.f(); // <- will call HelloTest::f() or Mock_HelloTest::f()
}
With this setup, you'd call RunHelloTest<HelloTest>() in your production code, and RunHelloTest<Mock_HelloTest>() in your test code.
There is no feature that control visibility/accessibility of class in C++.
Is there any way to fake it?
Are there any macro/template/magic of C++ that can simulate the closest behavior?
Here is the situation
Util.h (library)
class Util{
//note: by design, this Util is useful only for B and C
//Other classes should not even see "Util"
public: static void calculate(); //implementation in Util.cpp
};
B.h (library)
#include "Util.h"
class B{ /* ... complex thing */ };
C.h (library)
#include "Util.h"
class C{ /* ... complex thing */ };
D.h (user)
#include "B.h" //<--- Purpose of #include is to access "B", but not "Util"
class D{
public: static void a(){
Util::calculate(); //<--- should compile error
//When ctrl+space, I should not see "Util" as a choice.
}
};
My poor solution
Make all member of Util to be private, then declare :-
friend class B;
friend class C;
(Edit: Thank A.S.H for "no forward declaration needed here".)
Disadvantage :-
It is a modifying Util to somehow recognize B and C.
It doesn't make sense in my opinion.
Now B and C can access every member of Util, break any private access guard.
There is a way to enable friend for only some members but it is not so cute, and unusable for this case.
D just can't use Util, but can still see it.
Util is still a choice when use auto-complete (e.g. ctrl+space) in D.h.
(Edit) Note: It is all about convenience for coding; to prevent some bug or bad usage / better auto-completion / better encapsulation. This is not about anti-hacking, or prevent unauthorized access to the function.
(Edit, accepted):
Sadly, I can accept only one solution, so I subjectively picked the one that requires less work and provide much flexibility.
To future readers, Preet Kukreti (& texasbruce in comment) and Shmuel H. (& A.S.H is comment) has also provided good solutions that worth reading.
I think that the best way is not to include Util.h in a public header at all.
To do that, #include "Util.h" only in the implementation cpp file:
Lib.cpp:
#include "Util.h"
void A::publicFunction()
{
Util::calculate();
}
By doing that, you make sure that changing Util.h would make a difference only in your library files and not in the library's users.
The problem with this approach is that would not be able to use Util in your public headers (A.h, B.h). forward-declaration might be a partial solution for this problem:
// Forward declare Util:
class Util;
class A {
private:
// OK;
Util *mUtil;
// ill-formed: Util is an incomplete type
Util mUtil;
}
One possible solution would be to shove Util into a namespace, and typedef it inside the B and C classes:
namespace util_namespace {
class Util{
public:
static void calculate(); //implementation in Util.cpp
};
};
class B {
typedef util_namespace::Util Util;
public:
void foo()
{
Util::calculate(); // Works
}
};
class C {
typedef util_namespace::Util Util;
public:
void foo()
{
Util::calculate(); // Works
}
};
class D {
public:
void foo()
{
Util::calculate(); // This will fail.
}
};
If the Util class is implemented in util.cpp, this would require wrapping it inside a namespace util_namespace { ... }. As far as B and C are concerned, their implementation can refer to a class named Util, and nobody would be the wiser. Without the enabling typedef, D will not find a class by that name.
One way to do this is by friending a single intermediary class whose sole purpose is to provide an access interface to the underlying functionality. This requires a bit of boilerplate. Then A and B are subclasses and hence are able to use the access interface, but not anything directly in Utils:
class Util
{
private:
// private everything.
static int utilFunc1(int arg) { return arg + 1; }
static int utilFunc2(int arg) { return arg + 2; }
friend class UtilAccess;
};
class UtilAccess
{
protected:
int doUtilFunc1(int arg) { return Util::utilFunc1(arg); }
int doUtilFunc2(int arg) { return Util::utilFunc2(arg); }
};
class A : private UtilAccess
{
public:
int doA(int arg) { return doUtilFunc1(arg); }
};
class B : private UtilAccess
{
public:
int doB(int arg) { return doUtilFunc2(arg); }
};
int main()
{
A a;
const int x = a.doA(0); // 1
B b;
const int y = b.doB(0); // 2
return 0;
}
Neither A or B have access to Util directly. Client code cannot call UtilAccess members via A or B instances either. Adding an extra class C that uses the current Util functionality will not require modification to the Util or UtilAccess code.
It means that you have tighter control of Util (especially if it is stateful), keeping the code easier to reason about since all access is via a prescribed interface, instead of giving direct/accidental access to anonymous code (e.g. A and B).
This requires boilerplate and doesn't automatically propagate changes from Util, however it is a safer pattern than direct friendship.
If you do not want to have to subclass, and you are happy to have UtilAccess change for every using class, you could make the following modifications:
class UtilAccess
{
protected:
static int doUtilFunc1(int arg) { return Util::utilFunc1(arg); }
static int doUtilFunc2(int arg) { return Util::utilFunc2(arg); }
friend class A;
friend class B;
};
class A
{
public:
int doA(int arg) { return UtilAccess::doUtilFunc1(arg); }
};
class B
{
public:
int doB(int arg) { return UtilAccess::doUtilFunc2(arg); }
};
There are also some related solutions (for tighter access control to parts of a class), one called Attorney-Client and the other called PassKey, both are discussed in this answer: clean C++ granular friend equivalent? (Answer: Attorney-Client Idiom) . In retrospect, I think the solution I have presented is a variation of the Attorney-Client idiom.
This is purely a theoretical question, I know that if someone declares a method private, you probably shouldn't call it. I managed to call private virtual methods and change private members for instances, but I can't figure out how to call a private non-virtual method (without using __asm). Is there a way to get the pointer to the method? Are there any other ways to do it?
EDIT: I don't want to change the class definition! I just want a hack/workaround. :)
See my blog post. I'm reposting the code here
template<typename Tag>
struct result {
/* export it ... */
typedef typename Tag::type type;
static type ptr;
};
template<typename Tag>
typename result<Tag>::type result<Tag>::ptr;
template<typename Tag, typename Tag::type p>
struct rob : result<Tag> {
/* fill it ... */
struct filler {
filler() { result<Tag>::ptr = p; }
};
static filler filler_obj;
};
template<typename Tag, typename Tag::type p>
typename rob<Tag, p>::filler rob<Tag, p>::filler_obj;
Some class with private members
struct A {
private:
void f() {
std::cout << "proof!" << std::endl;
}
};
And how to access them
struct Af { typedef void(A::*type)(); };
template class rob<Af, &A::f>;
int main() {
A a;
(a.*result<Af>::ptr)();
}
#include the header file, but:
#define private public
#define class struct
Clearly you'll need to get around various inclusion guards etc and do this in an isolated compilation unit.
EDIT:
Still hackish, but less so:
#include <iostream>
#define private friend class Hack; private
class Foo
{
public:
Foo(int v) : test_(v) {}
private:
void bar();
int test_;
};
#undef private
void Foo::bar() { std::cout << "hello: " << test_ << std::endl; }
class Hack
{
public:
static void bar(Foo& f) {
f.bar();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Foo f(42);
Hack::bar(f);
system("pause");
return 0;
}
It can be called if a public function returns the address of the private function, then anyone can use that address to invoke the private function.
Example,
class A
{
void f() { cout << "private function gets called" << endl; }
public:
typedef void (A::*pF)();
pF get() { return &A::f; }
};
int main()
{
A a;
void (A::*pF)() = a.get();
(a.*pF)(); //it invokes the private function!
}
Output:
private function gets called
Demo at ideone : http://www.ideone.com/zkAw3
The simplest way:
#define private public
#define protected public
Followup on T.E.D.'s answer: Don't edit the header. Instead create your own private copy of the header and insert some friend declarations in that bogus copy of the header. In your source, #include this bogus header rather than the real one. Voila!
Changing private to public might change the weak symbols that result from inlined methods, which in turn might cause the linker to complain. The weak symbols that result from inline methods will have the same signatures with the phony and real headers if all that is done is to add some friend declarations. With those friend declarations you can now do all kinds of evil things with the class such as accessing private data and calling private members.
Addendum
This approach won't work if the header in question uses #pragma once instead of a #include guard to ensure the header is idempotent.
You have friend classes and functions.
I know that if someone declares a method private, you probably
shouldn't call it.
The point is not 'you shouldn't call it', it's just 'you cannot call it'. What on earth are you trying to do?
Call the private method from a public function of the same class.
Easiest way to call private method (based on previous answers but a little simpler):
// Your class
class sample_class{
void private_method(){
std::cout << "Private method called" << std::endl;
}
};
// declare method's type
template<typename TClass>
using method_t = void (TClass::*)();
// helper structure to inject call() code
template<typename TClass, method_t<TClass> func>
struct caller{
friend void call(){
TClass obj;
(obj.*func)();
}
};
// even instantiation of the helper
template struct caller<sample_class,&sample_class::private_method>;
// declare caller
void call();
int main(){
call(); // and call!
return 0;
}
Well, the obvious way would be to edit the code so that it is no longer private.
If you insist on finding an evil way to do it...well...with some compilers it may work create your own version of the header file where that one method is public instead of private. Evil has a nasty way of rebounding on you though (that's why we call it "evil").
I think the closest you'll get to a hack is this, but it's not just unwise but undefined behaviour so it has no semantics. If it happens to function the way you want for any single program invocation, then that's pure chance.
Define a similar class that is the same apart from the function being public.
Then typecast an object with the private function to one with the public function, you can then call the public function.
If we are speaking of MSVC, I think the simplest way with no other harm than the fact of calling a private method itself is the great __asm:
class A
{
private:
void TestA () {};
};
A a;
__asm
{
// MSVC assumes (this) to be in the ecx.
// We cannot use mov since (a) is located on the stack
// (i.e. [ebp + ...] or [esp - ...])
lea ecx, [a]
call A::TestA
}
For GCC it can be done by using mangled name of a function.
#include <stdio.h>
class A {
public:
A() {
f(); //the function should be used somewhere to force gcc to generate it
}
private:
void f() { printf("\nf"); }
};
typedef void(A::*TF)();
union U {
TF f;
size_t i;
};
int main(/*int argc, char *argv[]*/) {
A a;
//a.f(); //error
U u;
//u.f = &A::f; //error
//load effective address of the function
asm("lea %0, _ZN1A1fEv"
: "=r" (u.i));
(a.*u.f)();
return 0;
}
Mangled names can be found by nm *.o files.
Add -masm=intel compiler option
Sources: GCC error: Cannot apply offsetof to member function MyClass::MyFunction
https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html
After reading Search for an elegant and nonintrusive way to access private methods of a class, I want to sum up an ideal way since no one else has pasted it here:
// magic
//
template <typename Tag, typename Tag::pfn_t pfn>
struct tag_bind_pfn
{
// KEY: "friend" defines a "pfn_of" out of this template. And it's AMAZING constexpr!
friend constexpr typename Tag::pfn_t pfn_of(Tag) { return pfn; }
};
// usage
//
class A
{
int foo(int a) { return a; }
};
struct tag_A_foo
{
using pfn_t = int (A::*)(int);
// KEY: make compiler happy?
friend constexpr typename pfn_t pfn_of(tag_A_foo);
};
// KEY: It's legal to access private method pointer on explicit template instantiation
template struct tag_bind_pfn<tag_A_foo, &A::foo>;
inline static constexpr const auto c_pfn_A_foo = pfn_of(tag_A_foo{});
#include <cstdio>
int main()
{
A p;
auto ret = (p.*(c_pfn_A_foo))(1);
printf("%d\n", ret);
return 0;
}
I am trying to do unit testing (using the Boost unit testing framework) on a C++ class called VariableImpl. Here are the details.
class Variable
{
public:
void UpdateStatistics (void) {
// compute mean based on m_val and update m_mean;
OtherClass::SendData (m_mean);
m_val.clear ();
}
virtual void RecordData (double) = 0;
protected:
std::vector<double> m_val;
private:
double m_mean;
};
class VariableImpl : public Variable
{
public:
virtual void RecordData (double d) {
// Put data in m_val
}
};
How can I check that the mean is computed correctly? Note that 1) m_mean is protected and 2) UpdateStatistics calls a method of another class and then clears the vector.
The only way I can see would be to add a getter (for instance, GetMean), but I don't like this solution at all, nor I think it is the most elegant.
How should I do?
And what should I do if I were to test a private method instead of a private variable?
Well, unit testing should test units and ideally every class is a self-contained unit – this follows directly from the single responsibility principle.
So testing private members of a class shouldn’t be necessary – the class is a black box that can be covered in a unit test as-is.
On the other hand, this isn’t always true, and sometimes with good reasons (for instance, several methods of the class could rely on a private utility function that should be tested). One very simple, very crufty but ultimately successful solution is to put the following into your unit-test file, before including the header that defines your class:
#define private public
Of course, this destroys encapsulation and is evil. But for testing, it serves the purpose.
For a protected method/variable, inherit a Test class from the class and do your testing.
For a private, introduce a friend class. It isn't the best of solutions, but it can do the work for you.
Or this hack:
#define private public
In general, I agree with what others have said on here - only the public interface should be unit tested.
Nevertheless, I've just had a case where I had to call a protected method first, to prepare for a specific test case. I first tried the #define protected public approach mentioned above; this worked with Linux/GCC, but failed with Windows and Visual Studio.
The reason was that changing protected to public also changed the mangled symbol name and thus gave me linker errors: the library provided a protected __declspec(dllexport) void Foo::bar() method, but with the #define in place, my test program expected a public __declspec(dllimport) void Foo::bar() method which gave me an unresolved symbol error.
For this reason, I switched to a friend based solution, doing the following in my class header:
// This goes in Foo.h
namespace unit_test { // Name this anything you like
struct FooTester; // Forward declaration for befriending
}
// Class to be tested
class Foo
{
...
private:
bool somePrivateMethod(int bar);
// Unit test access
friend struct ::unit_test::FooTester;
};
And in my actual test case, I did this:
#include <Foo.h>
#include <boost/test/unit_test.hpp>
namespace unit_test {
// Static wrappers for private/protected methods
struct FooTester
{
static bool somePrivateMethod(Foo& foo, int bar)
{
return foo.somePrivateMethod(bar);
}
};
}
BOOST_AUTO_TEST_SUITE(FooTest);
BOOST_AUTO_TEST_CASE(TestSomePrivateMethod)
{
// Just a silly example
Foo foo;
BOOST_CHECK_EQUAL(unit_test::FooTester::somePrivateMethod(foo, 42), true);
}
BOOST_AUTO_TEST_SUITE_END();
This works with Linux/GCC as well as Windows and Visual Studio.
A good approach to test the protected data in C++ is the assignment of a friend proxy class:
#define FRIEND_TEST(test_case_name, test_name)\
friend class test_case_name##_##test_name##_Test
class MyClass
{
private:
int MyMethod();
FRIEND_TEST(MyClassTest, MyMethod);
};
class MyClassTest : public testing::Test
{
public:
// ...
void Test1()
{
MyClass obj1;
ASSERT_TRUE(obj1.MyMethod() == 0);
}
void Test2()
{
ASSERT_TRUE(obj2.MyMethod() == 0);
}
MyClass obj2;
};
TEST_F(MyClassTest, PrivateTests)
{
Test1();
Test2();
}
See more Google Test (gtest).
Unit test VariableImpl such that if its behavior is ensured, so is Variable.
Testing internals isn't the worst thing in the world, but the goal is that they can be anything as long as the interfaces contracts are ensured. If that means creating a bunch of weird mock implementations to test Variable, then that is reasonable.
If that seems like a lot, consider that implementation inheritance doesn't create great separation of concerns. If it is hard to unit test, then that is a pretty obvious code smell for me.
While in my opinion the need of testing private members/methods of a class is a code smell, I think that is technically feasible in C++.
As an example, suppose you have a Dog class with private members/methods except for the public constructor:
#include <iostream>
#include <string>
using namespace std;
class Dog {
public:
Dog(string name) { this->name = name; };
private:
string name;
string bark() { return name + ": Woof!"; };
static string Species;
static int Legs() { return 4; };
};
string Dog::Species = "Canis familiaris";
Now for some reason you would like to test the private ones. You could use privablic to achieve that.
Include a header named privablic.h along with the desired implementation like that:
#include "privablic.h"
#include "dog.hpp"
then map some stubs according to types of any instance member
struct Dog_name { typedef string (Dog::*type); };
template class private_member<Dog_name, &Dog::name>;
...and instance method;
struct Dog_bark { typedef string (Dog::*type)(); };
template class private_method<Dog_bark, &Dog::bark>;
do the same with all static instance members
struct Dog_Species { typedef string *type; };
template class private_member<Dog_Species, &Dog::Species>;
...and static instance methods.
struct Dog_Legs { typedef int (*type)(); };
template class private_method<Dog_Legs, &Dog::Legs>;
Now you can test them all:
#include <assert.h>
int main()
{
string name = "Fido";
Dog fido = Dog(name);
string fido_name = fido.*member<Dog_name>::value;
assert (fido_name == name);
string fido_bark = (&fido->*func<Dog_bark>::ptr)();
string bark = "Fido: Woof!";
assert( fido_bark == bark);
string fido_species = *member<Dog_Species>::value;
string species = "Canis familiaris";
assert(fido_species == species);
int fido_legs = (*func<Dog_Legs>::ptr)();
int legs = 4;
assert(fido_legs == legs);
printf("all assertions passed\n");
};
Output:
$ ./main
all assertions passed
You can look at the sources of test_dog.cpp and dog.hpp.
DISCLAIMER: Thanks to insights of other clever people, I have assembled the aforementioned "library" able to access to private members and methods of a given C++ class without altering its definition or behaviour. In order to make it work it's (obviously) required to know and include the implementation of the class.
NOTE: I revised the content of this answer in order to follow directives suggested by reviewers.
I generally suggest testing the public interface of your classes, not the private/protected implementations. In this case, if it can't be observed from the outside world by a public method, then the unit test may not need to test it.
If the functionality requires a child class, either unit test the real derived class OR create your own test derived class that has an appropriate implementation.
Example from the Google testing framework:
// foo.h
#include "gtest/gtest_prod.h"
class Foo {
...
private:
FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
int Bar(void* x);
};
// foo_test.cc
...
TEST(FooTest, BarReturnsZeroOnNull) {
Foo foo;
EXPECT_EQ(0, foo.Bar(NULL));
// Uses Foo's private member Bar().
}
The main idea is the use of the friend C++ keyword.
You can extend this example as follows:
// foo.h
#ifdef TEST_FOO
#include "gtest/gtest_prod.h"
#endif
class Foo {
...
private:
#ifdef TEST_FOO
FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
#endif
int Bar(void* x);
};
You can define the TEST_FOO preprocessor symbol in two ways:
within the CMakeLists.txt file
option(TEST "Run test ?" ON)
if (TEST)
add_definitions(-DTEST_FOO)
endif()
as arguments to your compiler
g++ -D TEST $your_args