Читать книгу Practical Go - Amit Saha - Страница 59

Listing 2.6: Unit test for the main package

Оглавление

// chap2/sub-cmd-arch/handle_command_test.go package main import ( "bytes" "testing" ) func TestHandleCommand(t *testing.T) { usageMessage := `Usage: mync [http|grpc] -h http: A HTTP client. http: <options> server Options: -verb string HTTP method (default "GET") grpc: A gRPC client. grpc: <options> server Options: -body string Body of request -method string Method to call ` // TODO Insert testConfigs from above byteBuf := new(bytes.Buffer) for _, tc := range testConfigs { err := handleCommand(byteBuf, tc.args) if tc.err == nil && err != nil { t.Fatalf("Expected nil error, got %v", err) } if tc.err != nil && err.Error() != tc.err.Error() { t.Fatalf("Expected error %v, got %v", tc.err, err) } if len(tc.output) != 0 { gotOutput := byteBuf.String() if tc.output != gotOutput { t.Errorf("Expected output to be: %#v, Got: %#v", tc.output, gotOutput) } } byteBuf.Reset() } }

Save Listing 2.6 as handle_command_test.go in the same directory as the main package (see Listing 2.2).

One behavior for which we haven't written a test is the main package calling the correct function from the cmd package when a valid sub-command is specified. Exercise 2.1 gives you an opportunity to do so.

EXERCISE 2.1: TESTING SUB-COMMAND INVOCATION Update the test for the handleCommand() function to verify that the correct sub-command implementation is invoked when a valid sub-command is specified. You will find the approach suggested for the solution to Exercise 1.1 useful here as well.

Practical Go

Подняться наверх