3 ms·
Chances are, if you are using mocks in Go, you are doing it wrong. Functions should take interfaces (not interface{}, but interfaces that list methods) and retu
by sethammons 9y ago
Chances are, if you are using mocks in Go, you are doing it wrong. Functions should take interfaces (not interface{}, but interfaces that list methods) and return structs. In your tests, you create a fake that meets the interface and pass that to your function under test.
If you have to test file io or DB interaction, you can either do the adapter pattern or, as I prefer, just actually use the filesystem and DB but with some test infrastructure around it.
- deleted 9y ago[deleted]
- AnimalMuppet 9y agoWhat's the difference here between a "fake" and a "mock"?
- sethammons 9y agoMight be splitting hairs. There are fakes, mocks, and stubs. Generally, mocks assert, stubs do not. Some folks define both stubs and mocks as fakes. This does not fit perfectly for Go. The "fake" in Go is just a struct that matches an interface but is purely for testing. It allows for dependency injection where you pass a fake designed for your test. It can have its own properties and helper methods, but the key thing is that it matches your interface. You don't make assertions against the fake like you would a mock. You assert against responses from your functions under test. Example: > type Bar interface{ > Walk() (int, error) > } > > func Visit(b Bar) (string, error) { ... some code ...} In the production code, you call Visit with some struct that matches the interface (has a Walk method). In tests, you create a new struct like fakeBar that also matches the interface. You can have your fakeBar return any string or error you like and you can verify that Walk behaves the way you need it to. Hope that helps.