Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active July 18, 2024 09:48
Show Gist options
  • Save Integralist/62a37111624853397982ac7c6369be19 to your computer and use it in GitHub Desktop.
Save Integralist/62a37111624853397982ac7c6369be19 to your computer and use it in GitHub Desktop.
[Golang f-tests replace table-driven tests] #go #golang #tests

https://itnext.io/f-tests-as-a-replacement-for-table-driven-tests-in-go-8814a8b19e9e

The following shows how to use sub-tests, which are nice because they give a visible name to each test and allow you to run each sub test in isolation:

func TestSomeFuncWithSubtests(t *testing.T) {
  f := func(t *testing.T, input, outputExpected string) {
    t.Helper()
    
    output := SomeFunc(input)
    if output != outputExpected {
      t.Fatalf("unexpected output; got %q; want %q", output, outputExpected)
    }
  }

  t.Run("first_subtest", func(t *testing.T) {
    f(t, "foo", "bar")
  })

  t.Run("second_subtest", func(t *testing.T) {
    f(t, "baz", "abc")
  })
}

The following is a combination of f-test style with table-driven style...

func TestThing_Success(t *testing.T) {
    f := func(t *testing.T, input1, input2 string, expected int) {
        // hoist the test code with assertions and clear args...
    }

    testcases := []struct{name, input1, input2 string, expected int}{
        {},
        // etc...
    }

    for _, tc := range testcases {
        t.Run(tc.name, func(t *testing.T) {
            f(t, tc.input1, tc.input2, tc.expected)
        })
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment