만든 기능을 설명할 때 Testable Examples를 사용하여 예시를 들고 테스트를 할 수 있다.
일반 테스트와 마찬가지로 파일명은 _test로 끝나야 한다. 또한 함수는 Example로 시작한다.
정수 두 개를 더하는 함수를 만들었다고 하자.
// in add.go
package gotest
func Add(a, b int) int {
return a + b
}
// in add_test.go
package gotest
import "fmt"
func ExampleAdd() {
for i := 1; i <= 4; i++ {
fmt.Println(Add(i, i+1))
}
// output:
// 3
// 5
// 7
// 9
}
출력될 것으로 예상하는 값을 // output: 아래 주석으로 적어주면 된다.
// output: 을 무조건 적어주어야 한다. 대소문자는 상관없다
// output: 이 없다면 테스트로 인식하지 못한다.
결과
~/Downloads/gotest $ go test -v 1
=== RUN ExampleAdd
--- PASS: ExampleAdd (0.00s)
PASS
ok gotest 0.238s
패키지를 한 번에 테스트하는 게 아니라면 아래처럼 함수를 정의한 go파일(add.go)도 인자로 함께 넣어주어야 한다.
$ go test add_test.go add.go
output을 다르게 적으면 친절하게 알려준다
~/Downloads/gotest $ go test -v 1
=== RUN ExampleAdd
--- FAIL: ExampleAdd (0.00s)
got:
3
5
7
9
want:
3
5
7
10
FAIL
exit status 1
FAIL gotest 0.116s
Testable Examples in Go - The Go Programming Language
Testable Examples in Go Andrew Gerrand 7 May 2015 Introduction Godoc examples are snippets of Go code that are displayed as package documentation and that are verified by running them as tests. They can also be run by a user visiting the godoc web page for
go.dev
Go’s Testable Examples under the hood
Hidden introduction to ast and parser packages
medium.com