samedi 30 janvier 2016

How can I mock Go functions in my tests?

I have read a few questions on StackOverflow that ask how functions such as time.Now() can be mocked. The solution seems to be to write a struct that implements a particular interface, and then in the tests, pass in that mock instead.

Is there a better way of doing this? Since there is no good enough implementation of a dependency injection container in Golang, I don't want to pass structs around manually, or to create a struct that only has something like this inside:

func (s MyStruct) Now() {
    return time.Now()
}

Because, first, I can't test this function. It might be nothing when you are dealing with one line that has no variables in it, but I have a function that connects to a TCP port. Doing stuff like this would require me to create adapters to everything it uses (eg net.Dial(), time.Now(), io.Copy(), bufio.Read(), and many others).

Second, since there is no DI, I will have to pass structs around, which will end up cluttering my code, rather than making it easier to read like DI does in other languages.

Aucun commentaire:

Enregistrer un commentaire