5 ms·
I like to use a pattern like this: given a resource defined as an interface: type Database interface { Users() ([]*User, error) } I like to cr
by dradtke 9y ago
I like to use a pattern like this: given a resource defined as an interface:
type Database interface {
Users() ([]*User, error)
}
I like to create an explicitly-mocked version of it like this:
type MockDatabase struct {
UsersStub func() ([]*User, error)
}
func (m MockDatabase) Users() ([]*User, error) {
if m.UsersStub == nil {
panic("MockDatabase.UsersStub is nil")
}
return (m.UsersStub)()
}
Then you can create the resources you need, and define how they work, at the top of your test:
func TestSomething(t *testing.T) {
db := MockDatabase{
UsersStub: func() ([]*User, error) {
...
}
}
// use db here
}
This works well as long as the things you're testing take all the resources they need as parameters.
- ihsw2 9y agoThis is pretty much it, mocking is quite simple and straightforward. It's tedious but wrapping access to external resources (eg: cache, HTTP, database) is necessary for a sane Go-based application.
- piinbinary 9y agoI also use that same pattern. I'm very tempted to write a tool to be called by `go generate` to automatically create that kind of mock.
- PopsiclePete 9y agoPlease don't. I mean, do, whatever makes you happy. There's at least 3 of these flying around in various stages of abandonment. Here's one: https://github.com/vektra/mockery https://github.com/vektra/mockery
- pstuart 9y agoLooks like there's an official tool: https://github.com/golang/mock https://github.com/golang/mock
- piinbinary 9y agoDo any of those build this style of mock? I looked around a while back and didn't come across one. edit: I looked again and found https://github.com/matryer/moq https://github.com/matryer/moq which seems similar