Читать книгу Practical Go - Amit Saha - Страница 33
Writing Unit Tests
ОглавлениеThe standard library's testing
package contains everything you need to write tests to verify the behavior of your application.
Let's consider the parseArgs()
function first. It is defined as follows:
func parseArgs(args []string) (config, error) {}
It has one input: a slice of strings representing the command-line arguments specified to the program during invocation. The return values are a value of type config
and a value of type error
.
The testConfig
structure will be used to encapsulate a specific test case: a slice of strings representing the input command-line arguments in the args
field, expected error value returned in the err
field, and the expected config
value returned in the embedded config
struct field:
type testConfig struct { args []string err error config }
An example test case is
{ args: []string{"-h"}, err: nil, config: config{printUsage: true, numTimes: 0}, },
This test case verifies the behavior when -h
is specified as the command-line argument when executing the application.
We add a few more test cases and initialize a slice of test cases as follows:
tests := []testConfig{ { args: []string{"-h"}, err: nil, config: config{printUsage: true, numTimes: 0}, }, { args: []string{"10"}, err: nil, config: config{printUsage: false, numTimes: 10}, }, { args: []string{"abc"}, err: errors.New("strconv.Atoi: parsing \"abc\": invalid syntax"), config: config{printUsage: false, numTimes: 0}, }, { args: []string{"1", "foo"}, err: errors.New("Invalid number of arguments"), config: config{printUsage: false, numTimes: 0}, }, }
Once we have defined the slice of test configurations above, we will iterate over them, invoke the parseArgs()
function with the value in args
, and check whether the returned values, c
and err
, match the expected values of type config
and error
, respectively. The complete test will appear as shown in Listing 1.2.