Jakub M. Jakub M. - 1 month ago 11
C++ Question

Unit test accessing private variables

I have a unit test class

Tester
; I want it to access private fields of a
Working
class.

class Working {
// ...
private:
int m_variable;
};

class Tester {
void testVariable() {
Working w;
test( w.m_variable );
}
}


I have the following options:


  • make m_variable
    public
    - ugly

  • make method
    test_getVariable()
    - overcomplicated

  • add
    friend class Tester
    to Working - then Working "knows" about the Tester explicitly, which is not good



My ideal would be

class Working {
// ...
private:
int m_variable;

friend class TestBase;
};

class TestBase {};

class Tester : public TestBase {
void testVariable() {
Working w;
test( w.m_variable );
}
}


where Working knows about TestBase but not each test... but it does not work. Apparently friendship does not work with inheritance.

What would be the most elegant solution here?

Answer

Generally, your unit tests should not evaluate private variables. Write your tests to the interface, not the implementation.

If you really need to check that a private variable has a particular characteristic, consider using assert() rather than trying to write a unit test for it.

A longer answer (written for C# rather than C++, but the same principles apply) is at http://stackoverflow.com/a/1093481/436641.

Comments