请注意结构体
S
实现了接口I
。我试图通过嘲笑MethodB的响应来测试MethodA。
sample.go:
package service
// This is implemented by S
type I interface {
MethodA(num int) int
MethodB(num int) int
}
type S struct {
num int
str string
}
func NewI(num int, str string) I {
return S{num, str}
}
func (s S) MethodA(num int) int {
resp := s.MethodB(num) // want to mock this
return 5 * resp
}
func (s S) MethodB(num int) int {
return num * 10
}
sample_test.go:
package service
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
type MockI struct {
MockMethodA func(num int) int
MockMethodB func(num int) int
}
func (m *MockI) MethodA(num int) int {
return m.MockMethodA(num)
}
func (m *MockI) MethodB(num int) int {
return m.MockMethodB(num)
}
var _ = Describe("MethodA", func() {
Context("MethodA", func() {
Describe("normal case", func() {
It("should give proper response", func() {
i := NewI(1, "test")
// have to mock methodB()
// something like this:
// i.MethodB = MethodB(num int) int{
// return <some_value>
// }
got := i.MethodA(10)
expected := 500
Expect(got).To(Equal(expected))
})
})
})
})
任何帮助都将不胜感激。谢谢
依赖项注入的用法是否有效?将MockI注入到将要测试的代码中。
func funcTobeTested(i I) {
i.MethodA(0)
}
然后在测试中:
mockI := MockI{}
// Will run the mock implementation of MethodA
funcTobeTested(mockI)
我认为您可以使用mock包来模拟接口,并使用mock软件包的.On
函数来模拟测试方法A中的方法B。