I'm new to golang and trying to write a simple learning app using the facebook package from https://github.com/huandu/facebook.
I was able to get the package and connect to facebook and hit the facebook API. This is great but testing is my concern.
At first I was simply calling the method and creating a facebook object inside of it. Then after some research I tried passing in the facebook method I wanted to mock. Realizing there were multiple methods I needed, I am convinced that passing an interface is the right way to go.
So I tried creating interfaces that the package would implement.
type IFbApp interface {
ExchangeToken(string) (string, int, error)
Session(string) IFbSession
}
type MyFbApp struct{}
func (myFbApp *MyFbApp) ExchangeToken(token string) (string, int, error) {
return myFbApp.ExchangeToken(token)
}
func (myFbApp *MyFbApp) Session(token string) IFbSession {
return myFbApp.Session(token)
}
type IFbSession interface {
User() (string, error)
Get(string, map[string]interface{}) (map[string]interface{}, error)
}
type MyFbSession struct{}
func (myFbSession *MyFbSession) User() (string, error) {
return myFbSession.User()
}
func (myFbSession *MyFbSession) Get(path string, params map[string]string) (map[string]string, error) {
return myFbSession.Get(path, params)
}
func SomeMethod() {
Facebook(fb.New("appId", "appSecret")); // fb calls package
}
func Facebook(fbI IFbApp) {
fbI.ExchangeToken("sometokenhere");
}
I cannot compile this code since I get an error
cannot use facebook.New("appId", "appSecret") (type *facebook.App) as type IFbApp in argument to Facebook:
*facebook.App does not implement IFbApp (wrong type for Session method)
have Session(string) *facebook.Session
want Session(string) IFbSession
Switching IFbSession to *facebook.Session would make it compile of course but then I need to mock methods from the Session struct as well.
My plan was to create mock structs that implement my interfaces in my test.go file and pass it to the methods under test. Is this the right way to go?
I'd like to stay pure golang as much as possible and stay away from mocking frameworks.
Thanks.