便利なExample
Goには標準出力をテストするための便利な仕組みがある
テスト対象のコード
package main import ( "fmt" "os" "strings" ) func main() { echo() } func echo() { fmt.Println(strings.Join(os.Args[0:], " ")) }
テストコード
package main import "os" func ExampleEcho() { os.Args = []string{"test", "test"} echo() // Output: // test test } func ExampleFailEcho() { os.Args = []string{"something", "toDo"} echo() // Output: // yatta }
結果
--- FAIL: ExampleFailEcho (0.00s) got: something toDo want: yatta FAIL exit status 1 FAIL _/Users/ono/dev/go/goRepo/ch01/ex01 0.007s
テストメソッド名をExampleで開始して、
//Output:コメントの次の行に
期待される標準出力の結果をコメントで記述すれば良い
// Output: // 期待される標準出力
シンプルすぎて若干珍妙に感じてしまう