5 Testing
This chapter covers software testing. We will split the content in two parts: - Fundamentals: Core concepts related to testing as a whole, to better understand testing holistically. - Unit tests: A focus on unit tests-related concepts to write better unit tests.
5.1 Fundamentals
In this section, we will explore fundamental testing concepts to help us framing a better idea of what testing is and why it matters in the end to write better software.
5.1.1 Avoiding Logic in Tests
Avoiding logic in tests in one of the most fundamental concepts to write more maintainable tests. Let’s first discuss an example to illustrate what logic means in tests.
Consider the following code, which calculates the total savings (or economy) we can realize by applying a discount percentage to a list of prices:
func economy(prices []float64, discountPercentage float64) float64 {
var total float64
for _, price := range prices {
total += price * (-discountPercentage / 100)
}
return total
}
Now, we want to write a unit test to validate this economy function. We might want to reuse the same logic as the function itself to compute the expected result in the test like this: