Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do mock a function using gomock in Go?

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
  1. Anyone could point out what am I doing wrong? do I need to initialize a mock object first? before mocking the method?

  2. If I make GetResponse to be private [getResponse], I wont be able to mock it right?

Appreciate the all help.. Thanks!

like image 605
saruberoz Avatar asked Mar 07 '14 20:03

saruberoz


People also ask

What is mock in unit test?

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.


1 Answers

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

  1. define an interface (e.g. FooInterface) that you want to mock
  2. use mockgen to generate a mock from that interface
  3. create a mockObj using the function NewMockFooInterface()
  4. mockObj will then have the methods you want to call (i.e. EXPECT())
like image 82
rob74 Avatar answered Oct 09 '22 12:10

rob74