0

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?

  • 1
    Why do you have a problem with `t.Fatal`? It seems to do what you want it to. https://golang.org/src/testing/testing.go?s=24932:24975#L706 There is also `t.Error` if you don't want to `FailNow`. https://golang.org/src/testing/testing.go?s=24630:24673#L694 – 425nesp May 20 '20 at 01:45
  • maybe `t.Fatal()` is a misnomer, I don't want the process to exit? –  May 20 '20 at 01:46
  • Yeah, `t.Fatal` does not exit the process. Your `defer`s will even still run. It only fails the test. – 425nesp May 20 '20 at 01:47

1 Answers1

4

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()
jkr
  • 17,119
  • 2
  • 42
  • 68