Go - code quality assurance - Automated Testing - fmt, Sprintf
Head First Go、 Jay McGavren(著)、O’Reilly Media)の Chapter 14(code quality assurance - Automated Testing)、p.416(Code Magnets)の解答を求めてみる。
コード
compare/larger.go
package compare
func Larger(a int, b int) int {
if a < b {
return a
}
return b
}
コード
campare/larger_test.go
package compare
import (
"fmt"
"testing"
)
func TestFirstLarger(t *testing.T) {
want := 2
got := Larger(2, 1)
if got != want {
t.Error(errorString(2, 1, got, want))
}
}
func TestSecondLarger(t *testing.T) {
want := 8
got := Larger(4, 8)
if got != want {
t.Error(errorString(4, 3, got, want))
}
}
func errorString(a int, b int, got int, want int) string {
return fmt.Sprintf("Larger(%d, %d) = %d, want %d", a, b, got, want)
}
入出力結果(Terminal, Zsh)
% go test
--- FAIL: TestFirstLarger (0.00s)
larger_test.go:12: Larger(2, 1) = 1, want 2
--- FAIL: TestSecondLarger (0.00s)
larger_test.go:19: Larger(4, 3) = 4, want 8
FAIL
exit status 1
FAIL compare 0.282s
% cat go.md
cat: go.md: No such file or directory
% cat go.mod
module compare
go 1.23.4
%