1

I'm trying to use gomock to mock an interface called SuccessHandler to test a function.

The interfaces I have:

type Item interface {
    SetResults(results string)
}

type SuccessHandler interface {
    HandleSuccess(item Item) error
}

And an implementation of Item:

type MyItem struct {
    Results string
}

func (i *MyItem) SetResults(results string) {
    i.Results = results
}

Note that since SetResults modifies the struct, it is always implemented on a pointer receiver.

All I want the mock to do is set the results of MyItem when HandleSuccess() gets called with MyItem as an argument, and modify the value of the argument. Here's what I tried doing for the mock:

var myItem *MyItem
mockSuccessHandler.EXPECT().HandleSuccess(gomock.Any()).
    Do(func(item Item) error {
        item.SetResults("results")
        myItem = item.(*MyItem)
        return nil
    }).SetArg(0, successItem)

This causes a panic with the following:

panic: reflect.Set: value of type *MyItem is not assignable to type MyItem [recovered]
    panic: reflect.Set: value of type *MyItem is not assignable to type MyItem

Then, I tried changing the variable to just being a struct:

var myItem MyItem
mockSuccessHandler.EXPECT().HandleSuccess(gomock.Any()).
    Do(func(item Item) error {
        item.SetResults("results")
        myItem = *item.(*MyItem)
        return nil
    }).SetArg(0, successItem)

This doesn't panic, but doesn't end up changing the value of Result.

Any ideas as to what I'm doing wrong?

robbieperry22
  • 1,753
  • 1
  • 18
  • 49

0 Answers0