tf icon indicating copy to clipboard operation
tf copied to clipboard

Using structs as test fixtures

Open elliotchance opened this issue 6 years ago • 0 comments

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.

elliotchance avatar Oct 11 '18 00:10 elliotchance