kzsnyk
kzsnyk

Reputation: 2211

How to test private member functions of a class using QTestLib?

I am using QTestLib for Unit Testing and i ask myself how to test private member functions of my classes. I would like to build a test suite for an in-house shared library.

What strategies do i have in Qt's context for this ?

I thought that testing private member functions through public members functions could be a good starting point :

class A {

   public:
      // add an extra function that is only relevant for testing
      int value() const {
         return theFunctionIWantToTest();
      }

   private:
      int theFunctionIWantToTest() {
         // implementation ..
      }      
}

But the problem is that i don't need this getter in the class A after testing.

I am not very experienced with QTestLib and so far i could not find anything in Qt's Doc related to this specific point.

Thanks.

Upvotes: 0

Views: 407

Answers (1)

Harri
Harri

Reputation: 364

Four possible solutions in reverse order of personal preference:

  1. Set #define private public before include the class header. Non-portable unfortunately. (or luckily as some will say).
  2. Declare your QTestLib test class to be a friend of class A
  3. Move the gist of the function into a dedicated function in a separate file that is clearly marked as private API and forwared the call from the member function. Think of the a_p.h headers used by Qt itself.
  4. Settle on testing the public interface only. I.e. either give up on the goal to test private functions or accept that the function simply should be public in the first place.

Upvotes: 1

Related Questions