1

When debug in GoLand, I found init function run before some unit test, but not run before some unit test. I have not set any configuration related to unit test and init function. For example:

function A:

package1/function a()

function B:

package2/function b()

function C:

package3/int()

init runs before a(), but not befor b(). It's so weired. I have not found any law.

dlsniper
  • 7,188
  • 1
  • 35
  • 44
neal
  • 164
  • 3
  • 15
  • The order in which init functions are executed is deterministic and specified in the language spec. You might have to move them around. – Volker Nov 29 '20 at 11:51

1 Answers1

1

Unit tests should test a single package. Packages that are not referred to (not imported) from the tested package may or may not be initialized, you should not assume anything about packages not imported.

You only have guarantees that init() functions of all imported packages will be called first (recursively). The rules are listed in Spec: Package initialization.

So if you test packagea which does not import packageb, there is no guarantee that init() functions of packageb will be run. If you need that, you have to import packageb.

See related question: Is it really bad to use init in go?

icza
  • 389,944
  • 63
  • 907
  • 827