Example tests (self documenting tests)
suggest changeExample tests check that the code compiles and that it prints the output recorded after // Output:. They also show up in the package documentation.
sum.go:
package sum
// Sum calculates the sum of two integers
func Sum(a, b int) int {
return a + b
}
sum_test.go:
package sum
import "fmt"
func ExampleSum() {
x := Sum(1, 2)
fmt.Println(x)
fmt.Println(Sum(-1, -1))
fmt.Println(Sum(0, 0))
// Output:
// 3
// -2
// 0
}
To execute your test, run go test in the folder containing those files OR put those two files in a sub-folder named sum and then from the parent folder execute go test ./sum. In both cases you will get an output similar to this:
ok so/sum 0.005s
If you are wondering how this is testing your code, here is another example function, which actually fails the test:
func ExampleSum_fail() {
x := Sum(1, 2)
fmt.Println(x)
// Output:
// 5
}
When you run go test, you get the following output:
$ go test
--- FAIL: ExampleSum_fail (0.00s)
got:
3
want:
5
FAIL
exit status 1
FAIL so/sum 0.006s
If you want to see the documentation for your sum package – just run:
godoc -http=:6060
go doc prints documentation in the terminal. The HTTP server is godoc (install golang.org/x/tools/cmd/godoc). Open http://localhost:6060/pkg/ and find the sum package. The documentation for Sum includes the example: