'panic: testing: Verbose called before Init

Trying to run https://github.com/adonovan/gopl.io/blob/master/ch8/cake/cake_test.go

but got

panic: testing: Verbose called before Init

goroutine 1 [running]:
testing.Verbose(...)
  /usr/lib/go-1.17/src/testing/testing.go:453
.../cake_test.init()

It says the error comes from cake_test.init(), yet the cake_test.go file doesn't contain init():

$ grep init cake_test.go | wc
      0       0       0

What exactly is the problem?



Solution 1:[1]

This happens because the testing package itself has a init to process test flags and you are callind Verbose to create a global variable

https://cs.opensource.google/go/go/+/refs/tags/go1.18:src/testing/testing.go;l=548

To avoid this you can:

  1. Use a ponter to function to capture testing.Verbose and use inside functions, after all initializations ( Verbose will be type func() bool) but I think this is complex
  2. Add a helper that creates a new default on each test with a safe call to testing.Verbose
  3. Create a constructor (instead a test helper) that fill with the most common options and you can set the value of Verbose on each test
  4. Create a two constructors, a second one that receive the value of Verbose

Also, Consider create a method Debug with same signature of Println, to call fmt.Println if Verbose is true

If you have a constructor, you can create a second field: Logger, with is a ponter to function with same signature as Println and you initialize with fmt.Println and in the tests you can set as t.Log to have a better experience

Of course perhaps some suggestions are more advanced than others, feel free to play a little bit and choose the best ones

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tiago Peczenyj