How can I mock something that gets called in a package init()
method?
For example:
main.go
var myService MyService = myservicepkg.New()
func init(){
response := myService.get()
}
func otherMethod(){
//do something
}
maintest.go
func Test_otherMethod(){
ctrl := NewController(t)
defer ctrl.Finish()
myServiceMock = myservicepkg.NewMock(myService)
myServiceMock.EXPECT().get().return("success")
}
The problem is that init()
is called before the service is replaced by the mock.
You will need to call the
otherMethod()
insideinit()
. It can't be called beforeinit()
otherwise.