Chapter 9. Testing
Programming is not easy; even the best programmers are incapable of writing programs that work exactly as intended every time. Therefore, an important part of the software development process is testing. Writing tests for our code is a good way to ensure quality and improve reliability.
Go includes a special program that makes writing tests easier: go test. To illustrate how go test works, let’s create some tests for the package we made in Chapter 8. In the chapter8/math folder, create a new file called math_test.go. The Go compiler knows to ignore code in any files that end with _test.go, so the code defined in this file is only used by go test (and not go install or go build).
The ~/src/golang-book/chapter8/math/math_test.go file should contain the same package math we saw before:
packagemath
Then we import the special testing package and define a function that starts with the word Test (case matters) followed by whatever we want to name our test. We’ll be testing the Average function we wrote before, so let’s name it TestAverage:
packagemathimport"testing"funcTestAverage(t*testing.T){v:=Average([]float64{1,2})ifv!=1.5{t.Error("Expected 1.5, got ",v)}}
For the body of the function, we invoke the Average function on a hardcoded slice of floats (Average([]float64{1,2})). We then take that value and compare it to 1.5 and if they’re not the same, we use the special t.Error function (which is very much like fmt.Println) to signal an error to ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access