I'm having hard times writing unit tests in Go due to external libraries which don't expose an interface (therefore not mockable) but only pure functions. Even big ones like Google don't, so I'm wondering whether my approach is good enough.
Wouldn't be good practice for libraries to provide interface
s instead of packages with only functions in order to let the user mock them?
The solution I came up with until now is wrap these packages with an interface's implementation but that seem like too much work.
I come with an example. My function could look like this
func AnyFunction() error {
sess := session.Get("blabla")
// logic in here...
}
where session is an imported package that returns a struct
. I can't mock the package session
.
For this case I'm going to write a SessionInterface
with an implementation, which internally calls session.
Ex:
type SessionInterface interface {
Get(s string) Session
}
type mySessionImpl struct {}
func (me *mySessionImpl) Get(s string) Session {
return session.Get(s)
}
For my tests now I can mock the SessionInterface and inject that one into my code