简体   繁体   中英

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.

Besides enabling you to easily mock these functions, writing 'adapters' (your own interface) for such things has the advantage of abstracting your code from any individual implementation.

Passing structs around in your code also keeps your app from external dependencies on some kind of injection framework (many of which just violate the principle of IOC anyway).

In addition to writing your own interfaces to these dependencies, certain design philosophies can help you to mock .

For example, using domain driven design patterns, you can simply mock your "repository" in unit tests rather than mocking a database library.

In Go, all of this ends up very clean, and succinct, without the burden of a horde of third party frameworks magically doing the work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM