Читать книгу Practical Go - Amit Saha - Страница 35
Listing 1.3: Test for the validateArgs()
function
Оглавление// chap1/manual-parse/validate_args_test.go package main import ( "errors" "testing" ) func TestValidateArgs(t *testing.T) { // TODO Insert definition tests[] slice as above for _, tc := range tests { err := validateArgs(tc.c) if tc. err != nil && err.Error() != tc.err.Error() { t.Errorf("Expected error to be: %v, got: %v\n", tc.err, err) } if tc.err == nil && err != nil { t.Errorf("Expected nil error, got: %v\n", err) } } }
In the same subdirectory as Listing 1.2, save Listing 1.3 to a file called validate_args_test.go
. Now run the tests using the go test
command. It will now run both the TestParseFlags
and TestValidateArgs
tests.
Finally, you will write a unit test for the runCmd()
function. This function has the signature runCmd(r io.Reader, w io.Writer, c config)
. We will define a set of test cases as follows:
tests := []struct { c config input string output string err error }{ { c: config{printUsage: true}, output: usageString, }, { c: config{numTimes: 5}, input: "", output: strings.Repeat("Your name please? Press the Enter key when done.\n", 1), err: errors.New("You didn't enter your name"), }, { c: config{numTimes: 5}, input: "Bill Bryson", output: "Your name please? Press the Enter key when done.\n" + strings.Repeat("Nice to meet you Bill Bryson\n", 5), }, }
The field c
is a config
object representing the incoming configuration, input
is the test input received by the program from the user interactively, output
is the expected output, and err
represents any error that is expected based on the test input and configuration.
When you write a test for a program where you have to mimic an input from the user, this is how you can create a io.Reader
from a string:
r := strings.NewReader(tc.input)
Thus, when the getName()
function is called with io.Reader r
as created above, calling scanner.Text()
will return the string in tc.input
.
To mimic the standard output, we create an empty Buffer
object that implements the Writer
interface using new(bytes.Buffer)
. We can then obtain the message that was written to this Buffer
using the byteBuf.String()
method. The complete test is shown in Listing 1.4.