英文:
Ginkgo: Mocking a method for unit test
问题
请注意,结构体 S
实现了接口 I
。
我正在尝试通过模拟来测试 MethodA 的 MethodB 响应。
sample.go:
package service
// 这是由 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) // 想要模拟这个方法
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")
// 必须模拟 methodB()
// 类似于这样:
// i.MethodB = MethodB(num int) int{
// return <some_value>
// }
got := i.MethodA(10)
expected := 500
Expect(got).To(Equal(expected))
})
})
})
})
任何帮助将不胜感激。谢谢!
英文:
Please note that struct S
implements the interface I
.
I'm trying to test MethodA by mocking the response from MethodB.
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))
})
})
})
})
Any help will be appreciated. Thanks!
答案1
得分: 1
使用依赖注入不行吗?将MockI注入到要测试的代码中。
func funcTobeTested(i I) {
i.MethodA(0)
}
然后在测试中:
mockI := MockI{}
// 将运行MethodA的模拟实现
funcTobeTested(mockI)
英文:
Wouldnt the usage of dependency injection work? Inject the MockI into the code that you will be testing.
func funcTobeTested(i I) {
i.MethodA(0)
}
And then on the test:
mockI := MockI{}
// Will run the mock implementation of MethodA
funcTobeTested(mockI)
答案2
得分: 0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论