Skip to content

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

@AmitKumarDas

Description

@AmitKumarDas
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions