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

Listing 1.2: Test for the parseArgs() function

Оглавление

// chap1/manual-parse/parse_args_test.go package main import ( "errors" "testing" ) func TestParseArgs(t *testing.T) { // TODO Insert definition tests[] array as earlier for _, tc := range tests { c, err := parseArgs(tc.args) if tc.result.err != nil && err.Error() != tc.result.err.Error() { t.Fatalf("Expected error to be: %v, got: %v\n", tc.result.err, err) } if tc.result.err == nil && err != nil { t.Errorf("Expected nil error, got: %v\n", err) } if c.printUsage != tc.result.printUsage { t.Errorf("Expected printUsage to be: %v, got: %v\n", tc.result.printUsage, c.printUsage) } if c.numTimes != tc.result.numTimes { t.Errorf("Expected numTimes to be: %v, got: %v\n", tc.result.numTimes, c.numTimes) } } }

In the same directory as you saved Listing 1.1, save Listing 1.2 into a file called parse_flags_test.go. Now run the test using the go test command:

$ go test -v === RUN TestParseArgs --- PASS: TestParseArgs (0.00s) PASS ok github.com/practicalgo/code/chap1/manual-parse 0.093

Passing in the -v flag when running go test also displays the test functions that are being run and the result.

Next, consider the validateArgs() function defined as func validateArgs(c config) error. Based on the function specification, we will once again define a slice of test cases. However, instead of defining a named struct type, we will use an anonymous struct type instead as follows:

tests := []struct { c config err error }{ { c: config{}, err: errors.New("Must specify a number greater than 0"), }, { c: config{numTimes: -1}, err: errors.New("Must specify a number greater than 0"), }, { c: config{numTimes: 10}, err: nil, }, }

Each test case consists of two fields: an input object, c, of type config, and the expected error value, err. The test function is shown in Listing 1.3.

Practical Go

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