Search code examples
c++unit-testingtesting

Unit testing c++. How to test private members?


I would like to make unit tests for my C++ application.

What is the correct form to test private members of a class? Make a friend class which will test the private members, use a derived class, or some other trick?

Which technique does the testing APIs use?


Solution

  • Typically, one only tests the public interface as discussed in the question's comments.

    There are times however when it is helpful to test private or protected methods. For example, the implementation may have some non-trivial complexities that are hidden from users and that can be tested more precisely with access to non-public members. Often it's better to figure out a way to remove that complexity or figure out how to expose the relevant portions publicly, but not always.

    One way to allow unit tests access to non-public members is via the friend construct.