Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
AmitKumarDas opened this issue Jul 5, 2024 · 0 comments
Open

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

AmitKumarDas opened this issue Jul 5, 2024 · 0 comments

Comments

@AmitKumarDas
Copy link
Collaborator

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
@AmitKumarDas AmitKumarDas changed the title til: go: test: table vs fn: t.Helper go: test: table vs fn: t.Helper Jul 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant