bldsh / dive

dive in to learn
Apache License 2.0
0 stars 0 forks source link

go: test: table vs fn: t.Helper #14

Open AmitKumarDas opened 2 weeks ago

AmitKumarDas commented 2 weeks ago
func TestStringsIndex(t *testing.T) {
  // Notice:
  // - No need of test struct definitions
  // - The args to f can be thought of as following:
  //   - First few args are given conditions
  //   - Last arg is always the want condition
  f := func(s, substr string, nExpected int) {
    t.Helper()

    n := strings.Index(s, substr)
    if n != nExpected {
      t.Fatalf("unexpected n; got %d; want %d", n, nExpected)
    }
  }

  // Notice: test description along with t.Helper is a nice combo

  // first chars match
  f("foobar", "foo", 0)

  // middle chars match
  f("foobar", "bar", 3)

  // no match
  f("foobar", "baz", -1)
}
- f() doesn’t accept t *testing.T arg (it can use the arg from the outer test function)
- The first line inside f() is [t.Helper()](https://pkg.go.dev/testing#T.Helper) call
- t.Helper prints the line with the corresponding f() call when some test fails
- So you do not need to name your test scenarios
- Instead you can use code comments with full explanation & context