It looks like you're testing a top level command. You might want to
consider using the testscript package, which provides a very concise way of
end-to-end testing this kind of thing.

e.g.

    mycommand -h
    cmp stdout expect-stdout

    -- expect-stdout --
    Expected output

See https://pkg.go.dev/github.com/rogpeppe/go-internal/testscript for more
details.

On Tue, 20 Oct 2020 at 05:02, Amit Saha <amitsaha...@gmail.com> wrote:

> 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.
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/CANODV3%3DsOA4FKakaQ0mrcC%3D-BnVNq8SdnvDHgXShmrRt-_upHw%40mail.gmail.com
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAJhgacjCaCOq%2BYHFmcoH7At30H%2Bmn7t2fSvw%2B_Av4%2BhqDeHQhg%40mail.gmail.com.

Reply via email to