I'm trying to write Go Unit Test using testify mocking library. I was following this blog http://goinbigdata.com/testing-go-code-with-testify/. I have passed the mocked interface to the newCalculator function but still Random1 of Random interface is getting called instead of Random1 function of struct randomMock.
calculator.go
package calculator
type Random interface {
Random1(limit int) int
}
func newCalculator(rnd Random) Random {
return calc{
rnd: rnd,
}
}
type calc struct {
rnd Random
}
func (c calc) Random1(limit int) int {
return limit
}
calculator_test.go
package calculator
import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"testing"
)
type randomMock struct {
mock.Mock
}
func (o randomMock) Random1(limit int) int {
args := o.Called(limit)
return args.Int(0)
}
func TestRandom(t *testing.T) {
rnd := new(randomMock)
rnd.On("Random1", 100).Return(7)
calc := newCalculator(rnd)
assert.Equal(t, 7, calc.Random1(100))
}
Output on running: go test
--- FAIL: TestRandom (0.00s)
calculator_test.go:22:
Error Trace: calculator_test.go:22
Error: Not equal:
expected: 7
actual : 100
Test: TestRandom
FAIL
exit status 1
I got it myself. I was missing the call to the struct rnd first.
func (c calc) Random1(limit int) int {
return c.rnd.Random1(limit)
}