Home > Software design >  Golang: Mock an interface method before Init method is called
Golang: Mock an interface method before Init method is called

Time:03-22

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.

CodePudding user response:

You will need to call the otherMethod() inside init(). It can't be called before init() otherwise.

CodePudding user response:

I found a workaround, you can prevent the init code from being executed in your test and test the method in isolation like this:

func init(){
  if strings.HasSuffix(os.Args[0], ".test") {
    log.Printf("skipping init() for testing")
  } else if strings.HasSuffix(os.Args[1], "-test") {
    log.Printf("skipping init() for testing")
  } else { 
     response := myService.get()
  }
}

This will prevent the init service calls from being called.

  • Related