How to make mock function using gomock in Go?

I'm new to Go and doing a little simple project + the habit of testing the habit, but I'm having problems setting up the test using the layout. In particular, when setting up a 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)
}

Every time I run this with

go test

I always get an error

undefined: sample.MOCK
undefined: sample.EXPECT
  • Can anyone point out what I'm doing wrong? Do I need to initialize the layout first? before taunting this method?

  • If I make GetResponse private [getResponse], can I fix it correctly?

Appreciate all the help .. Thanks!

+4
source share
3 answers

gomock, gomock GoDoc, . -, , , gomock ( sample.GetResponse), . -, " "

  • (, FooInterface),
  • mockgen
  • mockObj, NewMockFooInterface()
  • mockObj , ( EXPECT())
+6

:

  1. → - . Go. - , , - . , , .
  2. GoMock - Go. github.com/golang. Go API .
  3. gomock ( ), mockgen (, mockgen.exe PATH). GoMock :
    1. mockgen, , .
    2. gomock.Controller , .
    3. EXPECT() ,
    4. Finish() , ( testify, )

, mockgen, . → https://github.com/golang/mock mockgen ->

mockgen -destination={put the generated mocks in the file} -package={generate mocks for this package} {generate mocks for this interface}

https://blog.codecentric.de/en/2017/08/gomock-tutorial/

0

I am new to this, but have run into the same problem. You need to install Bazaar

http://wiki.bazaar.canonical.com/Download

Then install withmock

go get github.com/qur/withmock
go get github.com/qur/withmock/mocktest

Then at the command prompt run

$> withmock go test
-3
source

Source: https://habr.com/ru/post/1530673/


All Articles