问题描述
我有一个单元测试类 Tester
;我想要访问工作
类的私有字段。
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 );
}
}
我有以下选项:
- make m_variable
public
- 丑陋 - make方法
test_getVariable()
- 过度 - 添加
friend class Tester
知道关于测试器,这是不好的
- 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
我的理想是
class Working {
// ...
private:
int m_variable;
friend class TestBase;
};
class TestBase {};
class Tester : public TestBase {
void testVariable() {
Working w;
test( w.m_variable );
}
}
其中Working知道TestBase而不是每个测试。 。但它不工作。显然,友谊不能继承。
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?
推荐答案
,你的单元测试不应该评估私有变量。
Generally, your unit tests should not evaluate private variables. Write your tests to the interface, not the implementation.
如果你真的需要检查一个私有变量有一个特定的特性,考虑使用 assert ()
,而不是尝试为它编写一个单元测试。
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.
更长的答案(为C#而不是C ++,应用)位于。
A longer answer (written for C# rather than C++, but the same principles apply) is at http://stackoverflow.com/a/1093481/436641.
这篇关于单元测试访问私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!