嗨,我正在尝试在 GO 中模拟一个结构。我正在使用作证来做到这一点。但我似乎无法让它发挥作用,现在也不知道我做错了什么。下面是我拥有的示例 main.go 和 main_test.go 文件
// Arithmetic ...
type Arithmetic interface {
Add(int, int) int
Subtract(int, int) int
}
// MathOperation ...
type MathOperation struct {}
// GetNewArithmetic ...
func GetNewArithmetic(obj Arithmetic) Arithmetic {
if obj != nil {
return obj
}
return MathOperation{}
}
// Add ...
func (a MathOperation) Add(num1 int, num2 int) int {
return num1 + num2
}
// Subtract ...
func (a MathOperation) Subtract(num1 int, num2 int) int {
return num1 - num2
}
这是我的测试文件
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type MyMock struct {
mock.Mock
}
func (m *MyMock) Add(num1 int, num2 int) int {
args := m.Called(num1, num2)
return args.Int(0) + args.Int(1)
}
func (m *MyMock) Subtract(num1 int, num2 int) int {
args := m.Called(num1, num2)
return args.Int(0) + args.Int(1)
}
func TestDoComputation(t *testing.T) {
testobj := new(MyMock)
testobj.On("Add", 1, 2).Return(5)
// a := GetNewArithmetic(testobj)
result := GetNewArithmetic(testobj)
assert.Equal(t, 5, result.Add(5, 6))
testobj.AssertExpectations(t)
}
我收到此错误
--- FAIL: TestDoComputation (0.00s)
panic:
mock: Unexpected Method Call
-----------------------------
Add(int,int)
0: 5
1: 6
The closest call I have is:
Add(int,int)
0: 1
1: 2
[recovered]
panic:
mock: Unexpected Method Call
-----------------------------
Add(int,int)
0: 5
1: 6
The closest call I have is:
Add(int,int)
0: 1
1: 2
goroutine 13 [running]:
testing.tRunner.func1(0xc420106870)
/usr/lib/golang/src/testing/testing.go:711 +0x2d2
panic(0x701160, 0xc420011070)
我不知道如何修复,因为这是我第一次使用 Go 并使用 Testify 进行单元测试。如果有人可以看看并有一个工作版本,将不胜感激。谢谢