'How many scenarios should a unit test test?

Let's say there is a function:

type config struct {
    percent float64
    flat    float64
}

func Calculate(c *config, arrayofdata *arrayofdata) float64 {
    result := 0.0
    for _, data := range arrayofdata {
        value1 = data * percent
        value2 = flat
        result += math.Min(value1, value2)
    }
    return result
}

This simple calculate function simply calculates the result per data based on the flat value or the percent whichever is lower. And aggregates them.

If I were to write tests, how would you do it???

Do I have to have multiple test for each trivial scenario?

Say when value1 < value2 ?? TestCalculate/CorrectValue_FlatValueLessThanPercentValue

Say when value1 > value2 ?? TestCalculate/CorrectValue_FlatValueEqualToPercentValue

Check if flat is added per data?? So for 3 contents of arrayofdata, result = 3*config.flat?? TestCalculate/CorrectValue_FlatValuePerData

All these seem very trivial and can simply be combined into one test. what is the recommended way?

Like say a test where

config { percent: 1, flat: 20}

And then you put arrayofdata where each element checks for one of each case above written

arrayofdata: {
    1, // 1*percent < flat
    40, // 40*percent > flat
}

And the result would be correct if we add up the values, so you already check for case when more than one element in arrayofdata.

Is this a better approach? One test but combining the details. And separate tests for other cases like zero elements in arrayofdata etc.



Solution 1:[1]

I would recommend following the common practices in Clean Code, by Martin.Two of the discussed guidelines in particular are "One Assert per Test" and "Single Concept per Test".

When we have asserts that test more than 1 scenario and things start failing, it can become difficult to figure out which part is no longer passing. When that happens, you're going to end up splitting that unit test out into three separate test anyways.

Might as well start them out at 3 separate test, just keep your tests clean and expressive so if you come back to it months later you can figure out what unit test is doing what :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DPGraham4401