Testing methods which do yield return (deferred execution problem)

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 4.5 out of 5)
Loading ... Loading ...

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:

image

When called like this in my spec (test):

image 

Actually does nothing at all, so my specs would fail… it was really frustrating.

What can be done?

Actually, three things:

image

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!


Filed under: .NET, Best practices, C#
Written on: 14 May 2008 ·

kick it on DotNetKicks.com

Leave a Reply