如何对C ++类的私有成员(和方法)进行单元测试 [英] How to do unit testing on private members (and methods) of C++ classes
问题描述
我对单元测试很新,我有点困惑。
我试图在C ++上使用Boost单元测试框架进行单元测试类 VariableImpl
。以下是详细信息。
类变量
{
public:
void UpdateStatistics ){
//根据m_val计算平均值并更新m_mean;
OtherClass :: SendData(m_mean);
m_val.clear();
}
virtual void RecordData(double)= 0;
protected:
std :: vector< double> m_val;
private:
double m_mean;
};
class VariableImpl:public Variable
{
public:
virtual void RecordData(double d){
//将数据放入m_val
}
};
我的问题是如何检查平均值是否正确计算?注意1) m_mean
被保护,2) UpdateStatistics
调用另一个类的方法,然后清除向量。 / p>
我可以看到的唯一方法是添加一个getter(例如 GetMean
这样的解决方案,我也不认为它是最优雅的。
我应该怎么办?
如果我测试私有方法而不是私有变量,我该怎么办?
TIA,
Jir
那么,单元测试应该测试理想情况下每个类都是一个自包含单元 - 这直接来自单一的责任原则。
所以测试类的私有成员不应该是必需的 - 类是
另一方面,这并不总是真实的,有时有很好的理由(例如: ,类的几个方法可以依赖于应该测试的私有效用函数)。一个非常简单,非常简单但最终成功的解决方案是在之前将以下内容放入您的单元测试文件中,包括定义您的类的头文件:
#define private public
封装和邪恶。但对于测试,它的目的。
I am very new to unit testing and I am a little confused.
I am trying to do unit testing (using the Boost unit testing framework) on a C++ class called VariableImpl
. Here are the details.
class Variable
{
public:
void UpdateStatistics (void) {
// compute mean based on m_val and update m_mean;
OtherClass::SendData (m_mean);
m_val.clear ();
}
virtual void RecordData (double) = 0;
protected:
std::vector<double> m_val;
private:
double m_mean;
};
class VariableImpl : public Variable
{
public:
virtual void RecordData (double d) {
// put data in m_val
}
};
My question is how can I check that the mean is computed correctly? Note that 1) m_mean
is protected and 2) UpdateStatistics
calls a method of another class and then clears the vector.
The only way I can see would be to add a getter (for instance, GetMean
), but I don't like this solution at all, nor I think it is the most elegant.
How should I do?
And what should I do if I were to test a private method instead of a private variable?
TIA,
Jir
Well, unit testing should test units and ideally every class is a self-contained unit – this follows directly from the single responsibility principle.
So testing private members of a class shouldn’t be necessary – the class is a black box that can be covered in a unit test as-is.
On the other hand, this isn’t always true, and sometimes with good reasons (for instance, several methods of the class could rely on a private utility function that should be tested). One very simple, very crufty but ultimately successful solution is to put the following into your unit-test file, before including the header that defines your class:
#define private public
Of course, this destroys encapsulation and is evil. But for testing, it serves the purpose.
这篇关于如何对C ++类的私有成员(和方法)进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!