Assign the Perfom method to a global variable and re-assign it with a mocked one before running the test.
E.g.
51760447/a/a.go:
package a
type A struct{}
func (a *A) Perfom(url string) (string, error) {
return "real data", nil
}
51760447/caller.go:
package caller
import "github.com/mrdulin/golang/src/stackoverflow/51760447/a"
var s = a.A{}
var (
Perfom = s.Perfom
)
func Invoke(url string) string {
out, _ := Perfom(url)
return out
}
51760447/caller_test.go:
package caller_test
import (
"reflect"
"testing"
caller "github.com/mrdulin/golang/src/stackoverflow/51760447"
)
func TestInvoke(t *testing.T) {
oPerfom := caller.Perfom
perfomCallCount := 0
caller.Perfom = func(url string) (string, error) {
perfomCallCount++
return "fake data", nil
}
defer func() {
caller.Perfom = oPerfom
}()
got := caller.Invoke("localhost")
want := "fake data"
if !reflect.DeepEqual(got, want) {
t.Errorf("should return fake data, got:%v, want: %v", got, want)
}
if !reflect.DeepEqual(perfomCallCount, 1) {
t.Errorf("Perfom method should be called once, got:%d", perfomCallCount)
}
}
unit test result:
=== RUN TestInvoke
--- PASS: TestInvoke (0.00s)
PASS
coverage: 100.0% of statements
ok github.com/mrdulin/golang/src/stackoverflow/51760447 0.033s
coverage report:
