Search code examples
gogo-testing

Why doesn't t.Fail() accept string arguments?


I am trying to improve my Golang tests. And I was reading this: https://ieftimov.com/post/testing-in-go-failing-tests/

I was using t.Fatal("message") a lot, when instead I should have been using a combination of:

t.Fail()
t.Logf()

so why on Earth is there not a single call then can fail the test and log the reason why? Is there a way for me to add such a method to a test.Testing instance? I just want to do:

t.FailWithReason("the reason the test failed")

does this exist and if not can I add it somehow?


Solution

  • Take a look at the documentation and source code for the testing package.

    The documentation has an example of typical use:

    func TestAbs(t *testing.T) {
        got := Abs(-1)
        if got != 1 {
            t.Errorf("Abs(-1) = %d; want 1", got)
        }
    }
    

    The documentation for t.Errorf is:

    // Errorf is equivalent to Logf followed by Fail.
    

    which is very similar to what you say you want:

    t.Fail()
    t.Logf()