stretchr / testify

A toolkit with common assertions and mocks that plays nicely with the standard library
MIT License
23.23k stars 1.59k forks source link

Is there a way of mocking lambdas? #685

Open diegosanchez opened 5 years ago

diegosanchez commented 5 years ago

I cannot find ways of mocking lambdas on golang with testify though there is a way of mocking objects and their methods.

Would be desirable having the feature like this? I found useful being able to write a code like follow (the interface might be altered):

// holiday_calendar.go

// Other stuff
// ...
func (this *HolidayCalendar) callIfHoliday(date *MyDate, fn func()) {
  // even other some stuff    
  fn()
}

// holiday_calendar_test.go

func Test_Function(t *testing.T) {
    f := func(arg int, str string) {
      // Do your magic 
    }

    mock, task := MockLambda(f).On(1, "strArgument").ReturnNothing()
    calendar.callIfHoliday(NewMyDate(2020, 12, 25), task /* it's a func */).

    mock.verify(t)
}

I think you got the idea. The semantic equivalent code written in java might be like listed bellow:

Consumer task = Mockito.mock(Consumer.class);
calendar.callIfHoliday(new MyDate(2020, 12, 25), spy)

verify(task).accept(1, "strArgument");
diegosanchez commented 5 years ago

@ernesto-jimenez

Does it make sense for you?