Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we use interface for mocking methods Golang

I am new to Golang and have been exploring but not clear about mocking in unit tests. Can anyone explain following specific questions ?

Question1: For writing unit tests in Golang, why we need to have interfaces to mock methods, why not only struct ?

Question2: Why we inject the interface in struct(where we call external method)

With struct -

type GlobalData struct {}

var (
    GlobalObj = GlobalData{}
)

func (g GlobalData) GetGlobalData(a string) string{
    return a
}

With interface definition-

type GlobalInterface interface {
    GetGlobalData(a string) string
}

type GlobalData struct {}

var (
    GlobalObj = GlobalData{}
)

func (g GlobalData) GetGlobalData(a string) string{
    return a
}

Thanks

like image 265
Siyaram Malav Avatar asked Oct 15 '25 19:10

Siyaram Malav


1 Answers

Question 1: For writing unit tests in Golang, why we need to have interfaces to mock methods, why not only struct ?

Answer: Its not mandatory

Question 2: Why we inject the interface in struct(where we call external method)

Answer: Because, it helps you to replace the actual function call (that might trigger some out of scope actions as a part of unit test , such as database call, some API call etc) by injecting a MockStruct (which will be implementing the same interface that is there in the actual code). Polymorphism in simple words.

So, you create a MockStruct and define your own mockMethods to it. As polymorphism, your unit test pick MockStruct without complaining. Calling actual DB or http endpoints do not come under unit testing.

Just for reference, I can point you to one of my github codebase where I wrote a small test case for a file. As you can see I mocked :

  1. GuestCartHandler interface , that allowed me to not call the actual implementation
  2. Mocked sql connection using "github.com/DATA-DOG/go-sqlmock" package. This helped me to avoid establishing actual db client (so, no dependency of database while unit testing)

Let me know if you get the idea conceptually or do you need some more clarification.

like image 154
Shashank Vivek Avatar answered Oct 17 '25 09:10

Shashank Vivek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!