matryer / moq

Interface mocking tool for go generate
http://bit.ly/meetmoq
MIT License
2k stars 127 forks source link

API for argument-based assertions #187

Closed emil14 closed 1 year ago

emil14 commented 1 year ago

The only reason why I use gomock instead of this is that I can't simply do stuff like

v.EXPECT(1).RETURN(2)
v.EXPECT(2).RETURN(2)
v.EXPECT(3).RETURN(2)

I mean I have to write some if statements and so on. Looks like there's no easy way to configure several calls of mock. It looks especially complicated in a go-way-ish table-driven-tests

breml commented 1 year ago

I guess, supporting the same API as gomock is not a goal for moq. If you wish to have such an API, the simplest thing will be to stick with it.

That being said, there are small helpers that may simplify your life for use cases like the one above. Have a look at my comment in https://github.com/matryer/moq/issues/160#issuecomment-963643394.

The "pop" functionality mentioned in the above comment can now be moved to a generic function like this:

func pop[T any](t *testing.T, s *[]T) T {
        t.Helper()

        if len(*s) == 0 {
                t.Fatal("queue is already drained")
        }

        item := (*s)[0]
        *s = (*s)[1:]

        return item
}

With this, it becomes easy to place multiple different return values into a list (slice), which then can be placed in the test table for the table-driven tests.

breml commented 1 year ago

@matryer Maybe we could add such patterns to the documentation / README.md. What do you think?