elliotchance / tf

✔️ tf is a microframework for parameterized testing of functions and HTTP in Go.
MIT License
137 stars 3 forks source link

Using structs as test fixtures #14

Open elliotchance opened 5 years ago

elliotchance commented 5 years ago

I find that if i'm testing a function with several parameters or long inputs the code style becomes much less readable and I result to a loop like:

func TestStringSliceApply(t *testing.T) {
    StringSliceApply := tf.Function(t, luigi.StringSliceApply)

    for _, test := range []struct {
        items   []string
        fn      func(string) string
        returns []string
    }{
        {nil, nil, nil},
        {[]string{}, nil, []string{}},
        {[]string{"foo", "bar"}, nil, []string{"foo", "bar"}},
        {[]string{"FOO", " Bar"}, strings.ToLower, []string{"foo", " bar"}},
        {[]string{"Bar "}, strings.ToUpper, []string{"BAR "}},
    } {
        StringSliceApply(test.items, test.fn).Returns(test.returns)
    }
}

For:

func StringSliceApply(items []string, fn func(string) string) []string

It would be nice to use a struct that automatically maps the arguments, like:

func TestStringSliceApply(t *testing.T) {
    tf.AutoFunction(t, luigi.StringSliceApply, []struct {
        items   []string
        fn      func(string) string
        returns []string
    }{
        {nil, nil, nil},
        {[]string{}, nil, []string{}},
        {[]string{"foo", "bar"}, nil, []string{"foo", "bar"}},
        {[]string{"FOO", " Bar"}, strings.ToLower, []string{"foo", " bar"}},
        {[]string{"Bar "}, strings.ToUpper, []string{"BAR "}},
    })
}

I'm not sure if AutoFunction is a very good name.