简体   繁体   English

如何编写单元测试

[英]How to write a unit test

everyone.每个人。

I'm new to unit testing and can't get the idea of it.我是单元测试的新手,无法理解它。

I have a module that have a process() function.我有一个具有 process() 函数的模块。 Inside process() function module does a lot of non-trivial job.在 process() 函数模块内部做了很多重要的工作。 The task is to check module's output.任务是检查模块的输出。

For example, there is a method calculateDistance() inside process() method that calculates distance value.例如,process() 方法中有一个计算距离值的方法calculateDistance()。 Test requirement sounds like "check that module calculates distance..."测试要求听起来像“检查模块计算距离......”

As I understand I have to:据我了解,我必须:

  1. Prepare input data准备输入数据
  2. Call module's process() method调用模块的 process() 方法
  3. Calculate distance by hands用手计算距离
  4. Get module's output value for distance获取模块的距离输出值
  5. Compare this value to value calculated.将此值与计算值进行比较。

But it is easy for some trivial cases, for example some ariphmetical operations.但是对于一些琐碎的情况来说很容易,例如一些算术运算。 But what if inside calculateDistance() there are lots of formulas.但是如果在calculateDistance() 中有很多公式呢? How should I calculate this distance's value?我应该如何计算这个距离的值? Should I just copy all source code from calculateDistance() function to the test's code to calculate this value from step 3?我是否应该将calculateDistance() 函数中的所有源代码复制到测试代码中,以便从第3 步计算该值?

Here is the source code example:这是源代码示例:

void process(PropertyList& propList)
{
    m_properties = &propList;
    ...
    for (int i = 0; i < m_properties.propertiesCount; i++)
    {
        calculateDistance();
    }
}

void calculateDistance(int indx)
{
    Property& property = m_properties->properties[indx];
    property.distance = 0;

    for (int i = 0; i < property.objectsCount - 1; i++)
    {
        property.distance += getDistanceBetweenObjs(i, i + 1);
    }
}

int getDistanceBetweenObjects(indx1, indx2)
{
    // here is some complex algorithm of calculating the distance
}

So, my question is: should I prepare input data where I know the resulting distance value and just compare this value to the output value?所以,我的问题是:我应该在知道结果距离值的地方准备输入数据并将该值与输出值进行比较吗? Or should I get input data structures, calculate distance value the same way as calculateDistance() method does (here is code duplication) and compare this value to the output distance?或者我应该获取输入数据结构,以与 calculateDistance() 方法相同的方式计算距离值(这里是代码重复)并将该值与输出距离进行比较?

But what if inside calculateSmth() there are lots of formulas.但是如果在calculateSmth() 中有很多公式呢?

Refactor the code and break out those formulas to separate functions and test them individually.重构代码并分解这些公式以分离功能并单独测试它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM