devlooped / moq

The most popular and friendly mocking framework for .NET
Other
5.88k stars 800 forks source link

Add new verbs for SetupSequence such that the default response for an exhausted sequence can be defined. #1159

Open mikamins opened 3 years ago

mikamins commented 3 years ago

I'm attempting to upgrade from a very old version. Our codebase is relying on usage of SetupSequence that is no longer supported.

From https://github.com/moq/moq4/issues/467 by stakx:

What's probably missing with the new behaviour is methods on sequences such as .ReturnsByDefault and .ThrowsByDefault (or pick any other name) that define what the default response for an exhausted sequence should be. This can easily be added (now, or later).

Something like ReturnsByDefault would be great

Back this issue Back this issue

stakx commented 3 years ago

It's been a while since I wrote that. Today, I'm not so certain anymore whether that would be a good addition to the public API; it would mean a duplication of every existing method under SetupSequence (ReturnsReturnsByDefault, PassPassByDefault, ThrowsThrowsByDefault, including all of their various overloads). Whenever possible, I try to argue against such API "explosions", and I'm looking for solutions that don't require any additions, or at least smaller ones.

Moq 4 generally does not have a way of setting up the default behavior when no setup is available, except default value providers (which I'll get back to in a second), so it seems inconsistent to introduce such a mechanism for SetupSequence only.

It might be preferable instead to revert to the original behavior where a sequence setup becomes inactive once the sequence has been exhausted, thus allowing earlier, "shadowed" setups for the same method to be chosen once again. (That may not have been an option when I originally wrote the above quoted text, but it seems feasible today, after all the internal refactorings that have happened since.)

In the meantime, what you can do is set up a custom DefaultValueProvider on your mock... it will be invoked to provide a return value when a sequence setup has been "exhausted".

mikamins commented 3 years ago

Thanks for the information, and I completely understand your concerns about the API explosion. I will look into the workaround with DefaultValueProvider to see if that unblocks the upgrade effort on our repo

github-actions[bot] commented 3 weeks ago

Due to lack of recent activity, this issue has been labeled as 'stale'. It will be closed if no further activity occurs within 30 more days. Any new comment will remove the label.