-3

everyone.

I'm new to unit testing and can't get the idea of it.

I have a module that have a process() function. Inside process() function module does a lot of non-trivial job. The task is to check module's output.

For example, there is a method calculateDistance() inside process() method that calculates distance value. 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
  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. 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?

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?

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
  • 2
    SO is probably not the place to ask this question, there are plenty of good resources out there for unit testing. SO is more for specific software problems, show us example and we can help. – Mark Davies Aug 22 '18 at 15:30
  • Possible dup of: https://stackoverflow.com/questions/652292/what-is-unit-testing-and-how-do-you-do-it – Eljay Aug 22 '18 at 15:31

1 Answers1

-1

But what if inside calculateSmth() there are lots of formulas.

Refactor the code and break out those formulas to separate functions and test them individually.

klutt
  • 30,332
  • 17
  • 55
  • 95