mardi 25 septembre 2018

Attempted polymorphic call of mock types fail in Golang

I have the following mock type, created using Mockery.

type MyController interface{
  Foo(a string, b string) // this is auto-generated
  Bar(a string) // this method is auto-generated
}

type MyMock struct {
    mock.Mock
}

func (m *MyMock) Foo(a string, b string) {
  fmt.Println("MyMock Foo call")
}

func (m *MyMock) Bar(a string) {
  fmt.Println("MyMock Bar call")
}

then I defined a custom mock type:

type CustomMock struct {
  MyMock
  Cache map[string]string
}

so when I define my test suite

type myControllerSuite struct {
   myMock *MyMock
}

func (c *CustomMock) Foo(a string, b string) {
   fmt.Println("Custom Foo call")
}

func (c *CustomMock) Bar(a string) {
  fmt.Println("Custom Bar call")
}

func NewMyControllerSuite(
   myMock *MyMock,
) *myControllerSuite {
  return &myControllerSuite{
    myMock: myMock,
  }
}

and create a new myControllerSuite

customMock := &CustomMock{
  Cache: map[string]string{},
}

When I call the method as shown below:

NewMyControllerSuite(customMock).Foo("a", "b")

Invokes MyMock's Foo() instead of CustomMock, and I get the following error:

assert: mock: I don't know what to return because the method call was unexpected.
    Either do Mock.On("Foo").Return(...) first, or remove the Foo() call.

How can I accomplish the desired result, and call CustomMock's Foo() method instead?

Aucun commentaire:

Enregistrer un commentaire