Testing methods which do yield return (deferred execution problem)
Had a funny problem today. I’ve written a spec (tests) for a code that should have iterated over a collection of items and with some conditions do a yield return for each of them.
In it’s form, its a very simple piece of code, but somehow I could not for the light of me get the spec (test) to pass. It always seemed that the code didn’t even execute… I kept thinking to myself, WTF? This code is simple, and it does what it needs to!? Why doesn’t it pass? (as you can imagine I got a bit frustrated).
Then I remembered one *small* bit… yield return coupled with IEnumerable provides the deferred execution for my code, so this example:

When called like this in my spec (test):
Actually does nothing at all, so my specs would fail… it was really frustrating.
What can be done?
Actually, three things:

So:
s1) We are enumerating like we are expected to. This will execute the functionality
s2) We are manually assembling the enumerator and asking him to call our functionality
s3) We are feeding the deferred execution functionality to a new List which internally then executes it
I personally prefer and use option 3 now.
Hope this helps someone, it sure would me if I’ve remembered it out earlier.
Cheers!

(2 votes, average: 4.5 out of 5)
Leave a Reply