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

Updating the Unit Tests

Оглавление

We are going to finish off the chapter by updating the unit tests for the functions that we modified. Consider the parseArgs() function first. We will define a new anonymous struct for the test cases:

tests := []struct { args []string config output string err error }{..} The fields are as follows:

 args: A slice of strings that contains the command-line arguments to parse.

 config: An embedded field representing the expected config object value.

 output: A string that will store the expected standard output.

 err: An error value that will store the expected error.

Next, we define a slice of test cases representing the various test cases. The first one is as follows:

{ args: []string{"-h"}, output: ` A greeter application which prints the name you entered a specified number of times. Usage of greeter: <options> [name] Options: -n int Number of times to greet `, err: errors.New("flag: help requested"), config: config{numTimes: 0}, },

The preceding test cases test the behavior when the program is run with the -h argument. In other words, it prints the usage message. Then we have two test configs testing the behavior of the parseArgs() function for different values specified in the -n option:

{ args: []string{"-n", "10"}, err: nil, config: config{numTimes: 10}, }, { args: []string{"-n", "abc"}, err: errors.New("invalid value \"abc\" for flag -n: parse error"), config: config{numTimes: 0}, },

The final two test configs test the name specified as a positional argument:

{ args: []string{"-n", "1", "John Doe"}, err: nil, config: config{numTimes: 1, name: "John Doe"}, }, { args: []string{"-n", "1", "John", "Doe"}, err: errors.New("More than one positional argument specified"), config: config{numTimes: 1}, },

When “John Doe” is specified in quotes, it is considered valid. However, when John Doe is specified without quotes, they are interpreted as two positional arguments and hence the function returns an error. The complete test is provided in Listing 1.8.

Practical Go

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