I know that this is a debated practice, but let's suppose that this is the best option for me. I am wondering about what is the actual technique to do this. The approach that I see is this:
1) Make a friend class that of the class who's method I want to test.
2) In the friend class, create a public method(s) that call the private method(s) of the tested class.
3) Test the public methods of the friend class.
Here is a simple example to illustrate the above steps:
#include <iostream>
class MyClass
{
friend class MyFriend; // Step 1
private:
int plus_two(int a)
{
return a + 2;
}
};
class MyFriend
{
public:
MyFriend(MyClass *mc_ptr_1)
{
MyClass *mc_ptr = mc_ptr_1;
}
int plus_two(int a) // Step 2
{
return mc_ptr->plus_two(a);
}
private:
MyClass *mc_ptr;
};
int main()
{
MyClass mc;
MyFriend mf(&mc);
if (mf.plus_two(3) == 5) // Step 3
{
std::cout << "Passed" << std::endl;
}
else
{
std::cout << "Failed " << std::endl;
}
return 0;
}
Edit:
I see that in the discussion following one of the answers people are wondering about my code base.
My class has methods that are called by other methods; none of these methods should be called outside the class, so they should be private. Of course they could be put into one method, but logically they are much better separate. These methods are complicated enough to warrant unit testing, and due to performance issues I will very likely have to re-factor these methods, hence it would be nice to have a test to make sure that my re-factoring didn't break anything. I am not the only one working on the team, though I am the only one who is working on this project including the tests.
Having said the above, my question was not about whether it is a good practice to write unit tests for private methods, though I appreciate the feedback.