Ginkgo: Mocking a method for unit test

3.3k views Asked by At

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!

2

There are 2 answers

2
Denys Arturo Rosario Coste On

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)
0
Olaoye Oluwapelumi On

I think you can use the mockery package to mock the interface and use the .On function of mock package to mock just methodB in testing methodA.