Читать книгу Practical Go - Amit Saha - Страница 48
Listing 1.9: Test for runCmd()
function
Оглавление// chap1/flag-improvements/run_cmd_test.go package main import ( "bytes" "errors" "strings" "testing" ) func TestRunCmd(t *testing.T) { // TODO Insert test cases from above tests := []struct{..} byteBuf := new(bytes.Buffer) for _, tc := range tests { r := strings.NewReader(tc.input) err := runCmd(r, byteBuf, tc.c) if err != nil && tc.err == nil { t.Fatalf("Expected nil error, got: %v\n", err) } if tc.err != nil && err.Error() != tc.err.Error() { t.Fatalf("Expected error: %v, Got error: %v\n", tc.err.Error(), err.Error()) } gotMsg := byteBuf.String() if gotMsg != tc.output { t.Errorf("Expected stdout message to be: %v, Got: %v\n", tc.output, gotMsg) } byteBuf.Reset() } }
Save the Listing 1.9 code to a new file, run_cmd_test.go
, in the same directory as Listing 1.8.
Now, run all of the tests:
$ go test -v === RUN TestParseArgs --- PASS: TestParseArgs (0.00s) === RUN TestRunCmd --- PASS: TestRunCmd (0.00s) === RUN TestValidateArgs --- PASS: TestValidateArgs (0.00s) PASS ok github.com/practicalgo/code/chap1/flag-improvements 0.376s