2

we are using gopkg.in/mgo.v2/bson to talk with mongo, and its API populates passed structures instead returning results, for example:

func (p *Pipe) One(result interface{}) error {...

Problems occurs when I want to mock / test code which is using that. I want to both mock this execution and somehow get pupulated value in 'result'. Currently test has:

query.EXPECT().One(gomock.Any())

So as you can see I dont get any value, I just configure gomock to check that when I run my method then query.One has to be called. I cannot pass structure like

mystruct := MyStruct{}
query.EXPECT().One(&mystruct)

because mystruct in test code and in real code is different and verifing mock will fail (references are different). Im looking for something similar to mockito's argument captor: https://static.javadoc.io/org.mockito/mockito-core/2.6.9/org/mockito/ArgumentCaptor.html

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
hi_my_name_is
  • 4,894
  • 3
  • 34
  • 50

2 Answers2

7

This can be achieved via Do.

Copy & Paste of Github example from poy.

var capturedArgs []int

someMock.
  EXPECT().
  SomeMethod(gomock.Any()).
  Do(func(arg int){
    capturedArgs = append(capturedArgs, arg)
  })

Ref: https://github.com/golang/mock/pull/149

Paul Liang
  • 758
  • 8
  • 16
0

This project can help you: https://github.com/bouk/monkey. You can replace a function and use a bool variable to check the use.

called := false    
monkey.Patch(package.One, func(result interface{}) error {
    if result == expected {
       called := true
       return nil
    }
    return errors.new("not expected")
})

Dont't forget to restore your original function.

defer monkey.Unpatch(package.One)
Rodrigo Brito
  • 378
  • 3
  • 9
  • 1
    unfortunately the author of this library does not give permission to use this tool for any purpose https://github.com/bouk/monkey/blob/master/LICENSE.md – Marcin Kulik Jul 15 '20 at 13:57