Skip to content

proposal: testing: add assertion methods #52555

Closed

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.

Activity

  1. added this to the Proposal milestone on Apr 25, 2022
  2. seankhliao commented on Apr 25, 2022

    @seankhliao
    Member

    Note we recommend against assertion libraries in TestComments https://github.com/golang/go/wiki/TestComments#assert-libraries

  3. ianlancetaylor commented on Apr 25, 2022

    @ianlancetaylor
    Contributor

    See also https://go.dev/doc/faq#assertions. This is an intentional choice.

  4. icholy commented on Apr 26, 2022

    @icholy
  5. rsc commented on May 4, 2022

    @rsc
    Contributor

    This proposal has been declined as retracted.
    — rsc for the proposal review group

  6. moved this to Declined in Proposalson Aug 10, 2022
  7. removed this from Proposalson May 3, 2023
  8. locked and limited conversation to collaborators on May 4, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions