Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to assert one function or interface should be called? #586

Open
soluty opened this issue Sep 5, 2022 · 1 comment
Open

How to assert one function or interface should be called? #586

soluty opened this issue Sep 5, 2022 · 1 comment

Comments

@soluty
Copy link

soluty commented Sep 5, 2022

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

@onsi
Copy link
Owner

onsi commented Sep 10, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants