I am new to Go and doing small simple project + doing testing habit to learn.. but I am having trouble in setting up test using mock. Specifically in setting up the mock object
sample/sample.go
package sample
import (
"fmt"
"net/http"
)
func GetResponse(path, employeeID string) string {
url := fmt.Sprintf("http://example.com/%s/%s", path, employeeID)
// made some request here
// then convert resp.Body to string and save it to value
return value
}
func Process(path, employeeID string) string {
return GetResponse(path, employeeID)
}
sample/sample_test.go
package sample_test
import (
"testing"
"github.com/example/sample" // want to mock some method on this package
)
func TestProcess(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
sample.MOCK()SetController(ctrl)
sample.EXPECT().GetResponse("path", "employeeID").Return("abc")
v := sample.GetResponse("path", "employeeID")
fmt.Println(v)
}
Everytime I run this with
go test
I always get error
undefined: sample.MOCK
undefined: sample.EXPECT
Anyone could point out what am I doing wrong? do I need to initialize a mock object first? before mocking the method?
If I make GetResponse to be private [getResponse], I wont be able to mock it right?
Appreciate the all help.. Thanks!
unittest.mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.
I am not a gomock expert, but after reading the gomock GoDoc page, I see several issues with your code. First, you apparently can't use gomock to mock package functions (as you are trying to do with sample.GetResponse), only interfaces. Second, according to "standard usage", you have to
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With