Home > Mobile >  How to mock method in one struct golang
How to mock method in one struct golang

Time:08-22

I have a piece of code like this where Bar function called inside Foo function.

type MyInterface interface {
 Foo() bool
 Bar() bool
}

type MyStruct struct {
 ...
}

func NewFuncForDI() MyInterface {}

func (a *MyStruct) Foo() bool {
//...
fromBar := a.Bar()

return fromBar
}

func (a *MyStruct) Bar() bool {
//...
 return true
}

I'm using testify and it's work very well if I called another function from different struct, but how to mock a function called by another function in one struct? Is there any way I can make mock function for Bar?

CodePudding user response:

I don't think there is a clean way to do it in go. Unit tests will call all the mocks, integration tests will call the real implementations.

CodePudding user response:

It isn't possible to mock out just the Bar function. What you can do is convert the code that you want to mock in the Bar function into a variable on the MyStruct class and inject a mock value for that. For example, if Bar used time.Now(), you could modify MyStruct to be the following:

type MyStruct struct {
    nower func() time.Time
}

func (a *MyStruct) Bar() bool {
    now := a.nower()
}

Another alternative, is to replace concrete objects inside your struct with interfaces (s3iface vs s3 for example). Finally, if you're having trouble testing just one function on your struct it's probably a good indication that you need to split that code into a separate struct.

  • Related