Tuesday, February 7, 2017

Go - TestMain

Every day learning new things about Go, trapped into an interesting one. Apparently, not only you could test your main method, you should follow some well-defined practices.

First of all, it shouldn't be
func TestMain(t *testing.T) {
...
}

as usually, but
func TestMain(m *testing.M) {
...
}
So, the typical structure for the main_test.go would be:

func TestMain(m *testing.M) {
  setup()
  main()
  // or
  // go func() {
  //  main()
  // }()
  code := m.Run()
  tearDown()
  os.Exit(code)
}

func TestA(t *testing.T) {
...
}

func TestZ(t *testing.T) {
...
}

func TestB(t *testing.T) {
...


Interesting fact - tests would run in the order they are declared in the file, not alphabetically, which is usually what you want. 

No comments:

Post a Comment