0

I am writing unit tests for Method1()

I want to mock Method2() that is called from Method1() of the same interface.

We can mock methods of another interface easily by taking that mocked implementation in the struct. But I'm not sure how to mock a method of the same interface.

type ISample interface {
    Method1()
    Method2()
}

type Sample struct {
    
}

func (s Sample) Method1() {
    s.Method2()
}

func (s Sample) Method2() {
    
}
yashjain12yj
  • 723
  • 7
  • 19

1 Answers1

0

Can be solved by using an embedded interface.

type ISample interface {
    Method1()
    Method2()
}

type Sample struct {
    ISample
}

func (s Sample) Method1() {
    s.ISample.Method2()
}

func (s Sample) Method2() {
    
}

While creating an object of Sample, assign mocked ISample to ISample.

yashjain12yj
  • 723
  • 7
  • 19