How to test a class's private method?

Xie Bo
  • Xie Bo

    Xie Bo - 2006-08-20

    Hi all,

    Is it needed to test a class's private method for Unit Test? (I think the answer is YES because Unit Test means testing all methods) If so, how to test a class's private method by CPPUnit? Thanks!

    • John Dubchak

      John Dubchak - 2006-08-20

      It's a common understanding in the xUnit crowd that if you need to test a private method of a particular class, it's likely that the method needs to be refactored out into it's own public method, or extracted to another class entirely.

      Unit testing is a process to guarantee the public contract (public functions or methods) of a class that a client/caller will use.

      If this were Java and you were writing a jUnit test, you could label the method default scope and test it directly in the same package.  However, it's not and my recommendation without seeing what you're testing to consider the advice above.

      Sorry to sound pedantic.


      • Colin Peart

        Colin Peart - 2006-08-20

        jdubchak is right -- you probably shouldn't do this.  None the less, sometimes you need to be flexible.  When debugging a public interface, for example, sometimes is is useful to isolate a private method for testing -- and once you have written the test, why throw it away?

        I have done this before...  It was the very first time I found use for the friend keyword.  It is as wrong to use the friend keyword as it is to use a goto, but sometimes pragmatism needs to rule the day.  I don't remember the details of how to use it properly, you will have to look it up, but it does work.

    • ChinaMonkey

      ChinaMonkey - 2006-09-19

      I meet the same problem.
      Because the codes I want to test is done by other, so I can't don't want to change the private method to be public.
      And at last, I make my class derived from the class I want to test. In this way,I can access the private member function, but I don't know whether it is proper.

    • kaka

      kaka - 2006-11-08

      I think, you have to test a private method. Everything must be tested.

      easy, you can define everything as a macro

      so, example:

      #define private public
      #include <classyouwanttotestprivatemethod.h>
      #undef private

  • Vasudeva Kumar

    Vasudeva Kumar - 2009-11-27

    But with this macro we can compile without any problem but cannot link. Any suggestions


Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

No, thanks