Im trying to mock https://gopkg.in/olivere/elastic.v2 and its proven to be a nightmare. I usually use gomock but I can't because theres no interface file for the dep. What's the best way to go about this?
Create your own interface.
It doesn't even need to be complete, either, it only needs to cover the methods you actually use.
Suppose you have a type Foo
with the following methods: Bar()
, Baz()
, and Qux()
.
And you use this in your code:
func Frobnicate(f *Foo) err {
if err := f.Bar() error; err != nil {
return err
}
return nil
}
Just change this to use your new custom interface:
type barer interface() {
Bar() error
}
Then update your function signature:
func Frobnicate(f fooer) err {
// The rest the same as before
Now create your own fooer
implementation, and mock away.
If the type you need to mock is a simple struct with data, instead of with methods, you may wrap the method with getter/setter methods, so that an interface will work around it. Example, given this type:
type Foo struct {
Name string
}
You can create a wrapper:
type FooWrapper struct {
Foo
}
func (w *FooWrapper) Name() string {
return w.Foo.Name
}
Now the Foo
type can be accessed using a custom interface for mocking.