samedi 10 novembre 2018

Testing lifecyle in Go. Is it possible to add tear up and down method without duplication of code?

I started working with Go a month go. I come from java/kotlin background and I would like to understand if it's possible to achieve some of the same stuff that I did in those languages even in Go.

My current problem is this one.

I have a set of integration test cases where I need to initialize some stuff and then clean the resources: a common use case, I believe.

Here's some pseudo code of what I want achieve, if possible:

for each test {
  init resources
  run test {
     init test resources
     execute method under test
     assert
  }
  clean resources
}

At the moment, what I could try, was this approach:

func TestMain(m *testing.M) {
    setup()
    code := m.Run() 
    shutdown()
    os.Exit(code)
}

Which is fine generally speaking if not that it runs at package level. That doesn't give me much control at the moment because I would like to run one of those per test files. (that's what I noticed at least, please let me know if I'm wrong about it)

At the moment what I'm doing is basically run initialization for each test, but that's really a lot of duplicated code:

address, tearDownTestCase := testutils.SetupTestCase(emptyContext, postRouter(login.LoginUser), "/login")
defer tearDownTestCase()
// init test use case data
// run test
// clean use case data

Do you think there is a better approach?

Aucun commentaire:

Enregistrer un commentaire