我正在尝试使用 testify 模拟库编写 Go Unit Test。我正在关注这个博客http://goinbigdata.com/testing-go-code-with-testify/。我已将模拟接口传递给 newCalculator 函数,但仍然调用 Random 接口的 Random1 而不是 struct randomMock 的 Random1 函数。
计算器.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
}
计算器_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