I write tests and in this tests I work with some saved data files, DB records etc.
Should I remove this data before test ends?
For example, I check user
finder
func (ID int) User (*User) {
// my finder here
}
before test I have to create User
to DB. So, should I do something like
defer db.Clean()
???
same with files *os.File
If you are talking about unit testing your code, then there should be no call to the db. You should be using an interface that you can stub or mock.
So that we are all on the same page, there are a number of different forms of testing. Here we will consider unit testing and integration testing.
If you are unit testing, I would expect the use of mocks only, and no interaction with files. So I assume this is for some kind of integration testing.
This is a link to a bunch of slides, from a talk in testing by mitchellh the founder and CTO of hashicorp
One of the methods described in this talk is returning a func()
closure that's responsible for cleaning up afterwards.
You can encapsulate all your setup logic into a function that returns a cleanup closure.
func SetupIntegrationDB(t *testing.T, addr string) (*sql.DB, func()) {
// setup the connection, use t.Fatal for all errors.
cleanup := func() {
// here you have access to both t, and *sql.DB
// you can do all the clean up required,
// and return this anonymous function to be called later
}
return db, cleanup
}
// inside your test
db, cleanup := SetupIntegrationDB(t, addr)
defer cleanup()
This is very similar to what you suggested in your question, but allows for slightly improved encapsulation of the cleanup logic. All your tests just need to execute the cleanup function they are given, and not care about how it's done.
This same pattern can be used for files, returning the file (or an io.Writer
), and a function that knows where that file exists and can delete that file later on.