Skip to content

proposal: testing: add assertion methods #52555

@bkielbasa

Description

@bkielbasa

It's very common to use packages like testify or is as a set of helper methods that make testing code more readable. The reason behind using packages like that is to avoid writing repetitive code like the following.

func TestAddition(t *testing.T) {
  given := 2+4
  expected := 4

  if given != expected {
    t.Errorf("expected %d but %d given", expected, given)
  }
}

The if statement with the error message can be repeated even a hundred times. That's why we use external libraries to avoid that.

As we have generics in the language, we can make use of it and provide a new method in testing.T and testing.B:

func (t T) Equal[T comparable](expected, given T) {
  // comparing
  t.Fail()
}

func (t T) Equalf[T comparable](expected, given T, format string, args ...string) {
  // comparing
  t.Fail()
}

The first snipped would be simplified into:

func TestAddition(t *testing.T) {
  given := 2+4
  expected := 4

  t.Equal(expected, given)
}

func TestAddition2(t *testing.T) {
  given := 2+4
  expected := 4

  t.Equalf(expected, given, "math should always work")
}

Using generics has a big benefit over using any - we have a compile-time type check.

I know that saving those 2 lines of code doesn't seem to be a big win but please remember that the code may be repeated many times in a single test file.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions