gomega icon indicating copy to clipboard operation
gomega copied to clipboard

How to assert one function or interface should be called?

Open soluty opened this issue 3 years ago • 1 comments

i want to assert when condition match will call a function or not call a funcion

i search predefind matcher there is nothing like FunctionCalled matcher.

and when i try to implement matcher Match(actual interface{}) (success bool, err error)

but i v no idea how to do it

soluty avatar Sep 05 '22 13:09 soluty

hey there,

sorry for the delay. in general the way one approaches this in Go is to inject a fake or mock function. Gomega doesn't have any additional/direct support for fakes/mocks (though there are libraries out there such as counterfeiter).

In general this looks something like:


// Your code - obviously this is overly simplistic but you will need a way to inject the function/callback/interface that will be called if the condition is satisfied
func ThingBeingTested(callback func()) {
    if (...) {
        callback()
    }
}

// Your test

It("calls the callback if satisfied", func() {
     wasCalled := false
     fake := func() {
          wasCalled = true
     }
     ThingBeingTested(fake)
     Expect(wasCalled).To(BeTrue())
})

Libraries like counterfeiter allow you to generate fake versions of interfaces that you can inject in in this way. You can then make assertions on what was called on the fake and what was passed in to those invocations.

onsi avatar Sep 10 '22 15:09 onsi