AngryDuck
AngryDuck

Reputation: 4607

Is it possible to call private functions from a test class QT

I'm implementing a test class for my project in QT. I have added tests for all the public functions, however there are a couple of private functions that id like to include in my testing.

Obviously this wont work because they are private member functions, but i wondered if this is able to be bypassed on the basis i want to access them from a test case, i dont particularly want to change my code so that my tests work because thats not really helpful, id like the functions to be private but i also want to be able to test them.

Just wondering if anyone has any ideas on whether this is possible or if i need to change my functions to protected or something and then inherit the class for my test?

Upvotes: 2

Views: 1053

Answers (2)

Semih Yagcioglu
Semih Yagcioglu

Reputation: 4101

It is common practice to only unit test public functions but you can make the test class as the friend of the original class. Something like that:

The decleration of friend should be inside a #define UNIT_TEST flag.

#include <iostream>

class ToTestClass 
{
 #ifdef UNIT_TEST
    // ToTestClass declares TesterClass as a friend.
    friend class TesterClass;
 #endif

private:
    void privateMethod()
    {
        std::cout << "hey there" << std::endl;
    }
};

class TesterClass
{
public:
    TesterClass()
    {
        ToTestClass  totest;
        // TesterClass now has access to ToTestClass's private members and methods.
        totest.privateMethod();
    }
};

int main()
{
    TesterClass tester;
    return 0;
}

Upvotes: 2

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133014

Option one. Your functions may be conditionally public private

#ifdef UNIT_TEST
#define ut public
#else
#define ut private

class Testee
{
    public:
    ....


    ut:
    //private functions to be tested


    ptivate:
};

Then, in your test header, simply

#define UNIT_TEST
#include <Testee.h>

This is a bit dangerous if the tests and the application are in the same project (program) because according to the standard the class definitions must be the same in all translation units in a same program, otherwise, undefined behavior.

Second, and easier and safer option is to declare the Tester class as a friend.

class Testee
{
    public:
    ....

    ptivate:
    ....
    friend class Tester;
};

Upvotes: 1

Related Questions