Amit Saha
unread,Oct 20, 2020, 12:03:31 AM10/20/20Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to golang-nuts
Hi all, Consider the following test configuration:
func TestHandleCommand(t *testing.T) {
type expectedResult struct {
output string
err error
}
type testConfig struct {
args []string
result expectedResult
}
testConfigs := []testConfig{
testConfig{
args: []string{"-h"},
result: expectedResult{
err: nil,
output: `Expected output`,
},
},
}
Then, I do this:
for _, tc := range testConfigs {
byteBuf := new(bytes.Buffer)
w := bufio.NewWriter(byteBuf)
err := handleCommand(w, tc.args)
if tc.result.err == nil && err != nil {
t.Errorf("Expected nil error, got %v", err)
}
if tc.result.err != nil && err.Error() != tc.result.err.Error() {
t.Errorf("Expected error %v, got %v", tc.result.err, err)
}
if len(tc.result.output) != 0 {
w.Flush()
gotOutput := byteBuf.String()
if tc.result.output != gotOutput {
t.Errorf("Expected output to be: %v, Got: %v",
tc.result.output, gotOutput)
}
}
}
}
The above pattern works for me since the function may return an error
and/or it may have something it writes to the provided writer, w.
Is there a more concise way to write this?
Thanks,
Amit.