by dradtke · 8y ago · 0 comments
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.Here's one:
edit: I looked again and found https://github.com/matryer/moq which seems similar