How do I unit test a protected method in C++?

后端 未结 6 1671
遇见更好的自我
遇见更好的自我 2020-12-28 16:57

How do I unit test a protected method in C++?

In Java, I\'d either create the test class in the same package as the class under test or create an anonymous subcla

6条回答
  •  被撕碎了的回忆
    2020-12-28 17:32

    Assuming you mean a protected method of a publicly-accessible class:

    In the test code, define a derived class of the class under test (either directly, or from one of its derived classes). Add accessors for the protected members, or perform tests within your derived class . "protected" access control really isn't very scary in C++: it requires no co-operation from the base class to "crack into" it. So it's best not to introduce any "test code" into the base class, not even a friend declaration:

    // in realclass.h
    class RealClass {
        protected:
        int foo(int a) { return a+1; }
    };
    
    // in test code
    #include "realclass.h"
    class Test : public RealClass {
        public:
        int wrapfoo(int a) { return foo(a); }
        void testfoo(int input, int expected) {
            assert(foo(input) == expected);
        }
    };
    
    Test blah;
    assert(blah.wrapfoo(1) == 2);
    blah.testfoo(E_TO_THE_I_PI, 0);
    

提交回复
热议问题