views:

491

answers:

5

What is the best way to unit test a protected method in C++?

In Java, I'd either create the test class in the same package as the class under test or create an anonymous subclass that exposes the method I need in my test class. Because neither of those methods are available to me in C++, what are suggested approaches for testing protected methods in C++ classes?

I am testing an unmanaged C++ class using NUnit.

+2  A: 

One approach :

http://praveen.kumar.in/2008/01/02/how-to-unit-test-c-private-and-protected-member-functions/

Roopesh Majeti
It's probably best to summarize that blog post in your answer and then point to the link for details, that way, if the link becomes stale, you still have a viable answer.
zdan
A: 

Consider a public, possibly static 'unit test' function.

Ugly, but better than the alternatives I can think of using macros or friends or such.

Will
+2  A: 

Declare a friend class MyClass_UnitTest; in your MyClass. You can then define MyClass_UnitTest elsewhere in your unit test program that has full access to MyClass internals, but you don't have to provide an implementation in your release application. See CppUnit documentation for a good example of how this is done.

Rob K
+4  A: 

Assuming you mean a protected method of a publicly-accessible class:

In the test code, define a derived class of the class under test (either directly, or from one of its derived classes). Add accessors for the protected members, or perform tests within your derived class . "protected" access control really isn't very scary in C++: it requires no co-operation from the base class to "crack into" it. So it's best not to introduce any "test code" into the base class, not even a friend declaration:

// in realclass.h
class RealClass {
    protected:
    int foo(int a) { return a+1; }
};

// in test code
#include "realclass.h"
class Test : public RealClass {
    public:
    int wrapfoo(int a) { return foo(a); }
    void testfoo(int input, int expected) {
        assert(foo(input) == expected);
    }
};

Test blah;
assert(blah.wrapfoo(1) == 2);
blah.testfoo(E_TO_THE_I_PI, 0);
Steve Jessop
+1  A: 

I use CxxTest and have the CxxTest derive from the class that contains the protected member function. If you're still searching around for your favorite C++ Unit Testing framework, take a look at this article.

Pete