如何在C ++中单元测试受保护的方法? [英] How do I unit test a protected method in C++?
问题描述
如何在C ++中单元测试受保护的方法?
在Java中,我将在与测试类相同的包中创建测试类,或者创建一个匿名子类,暴露我在测试类中需要的方法,但是这些方法在C ++中都不适用于我。
我使用NUnit测试非托管C ++类。
在测试代码中,定义一个派生类的测试类(直接或从其派生类之一)。为受保护的成员添加访问器,或在您的派生类中执行测试。 protected访问控制在C ++中真的不是很可怕:它不需要基类的协作来破解它。所以最好不要在基类中引入任何测试代码,即使是一个朋友声明:
// in realclass .h
class RealClass {
protected:
int foo(int a){return a + 1; }
};
//在测试代码中
#includerealclass.h
class Test:public RealClass {
public:
int wrapfoo {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);
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 subclass that exposes the method I need in my test class, but neither of those methods are available to me in C++.
I am testing an unmanaged C++ class using NUnit.
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);
这篇关于如何在C ++中单元测试受保护的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!