unit-testingqtclassprivate-membersmetaobject

Is it possible in Qt to unit test (access) private methods?


I'm writing unit tests for my app, and now I've stumbled on a class in which I should test private methods. This could be result of poor design of particular class, but I must do it. Is there any way in Qt to call private methods, maybe using QMetaObject or something similar ?

For unit testing I am using QTestLib framework.


Solution

  • The proper (read annoying) answer is that you should not be testing private methods, those are implementation details ;-).

    OTOH -- have you thought about conditionally declaring them protected/private depending on whether you are in testing or no and then extending? I've used that to get me out of a similar pinch in the past.

    #ifdef TESTING
    // or maybe even public!
    #define ACCESS protected
    #else
    #define ACCESS private
    #endif
    
    /* your class here */
    class Foo {
    ACCESS
        int fooeyness;
    }
    
    // or better yet, place this in a different file!
    #ifdef TESTING
    /*
        class which extends the tested class which has public accessors
    */
    #endif