0

I am pretty new to Golang and writing unit test for a function (I am using stretchr testify for mocks). This function however calls another function in same class. But when unit testing the first function, I want to mock the call to second function because I do not want it to call the second function in real. This was easy in Java, but I am not finding any useful information for this in Go. Here is some code snippet for my functions:

func (p *Prod) GetProducts(name string, request *prod.ProductRequest) (detail *prod.Department, err error) {
    ....
    ....
    if err = p.getDetails(ctx, detail.Id); err != nil {
        logger.Error(err)
        return
    }
    
    ...
    ...
}

func (p *Prod) GetDetails(name string, Id string) error {
    ....
    ....
}

As you can see here, GetProducts is the function that I am trying to unit test and this function calls GetDetails. I would like to mock the call to GetDetails. Is this possible in Go? Do we typically mock such function calls in Go. Is it recommended? If yes, whats the right way to do it?

In my test, I have:

for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
    p := &Prod{
        ...
        ds:     tt.fields.ds,

    }
    p.GetProducts("somestring", request)
    })
}

This calls the function GetProducts. But now I don't know what changes to make so the call to GetDetails can be mocked. I would appreciate any help on this

  • 1
    I don't think is possible. Check this Github issue https://github.com/stretchr/testify/issues/29. The solution would be to separate concerns if possible – Pablo Flores Mar 26 '21 at 18:01
  • @PabloFlores What exactly do you mean by "The solution would be to separate concerns if possible"? Can you elaborate? – sunnyshine7890 Mar 26 '21 at 18:08
  • 1
    Depending on the responsibilities of your struct, it may be worth adding a new interface (ProdDetailer or something like that) whose responsibility is fetching Details. This way you can pass the interface as a parameter to GetProducts or add it as another field inside your Prod struct. Interfaces are really easy to mock in golang – Pablo Flores Mar 26 '21 at 21:37
  • 1
    You can even embed the ProdDetailer interface to your Prod struct in order to avoid dramatic changes in your API design – Pablo Flores Mar 26 '21 at 21:39

0 Answers0