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!
Wouldnt the usage of dependency injection work? Inject the MockI into the code that you will be testing.
And then on the test: