C #, NUnit: how to deal with exception testing and delayed execution

Let's say we have a method that looks like this:

public IEnumerable<Dog> GrowAll(this IEnumerable<Puppy> puppies)
{
    if(subjects == null)
        throw new ArgumentNullException("subjects");

    foreach(var puppy in puppies)
        yield return puppy.Grow();
}

If I check this by doing this:

Puppy[] puppies = null;
Assert.Throws<ArgumentNullException>(() => puppies.GrowAll());

Test fail to say that he

Expected: <System.ArgumentNullException>
But it was:null

I can fix this by changing the test to

Puppy[] puppies = null;
Assert.Throws<ArgumentNullException>(() => puppies.GrowAll().ToArray());

Is that how you usually do it? Or is there a better way to write a test? Or maybe the best way to write the method itself?


Tried to do the same with the built-in method Select, and it failed even without ToArrayor something like that, so apparently you can do something with this ... I just don't know what: p

+5
source share
1 answer

- . , , , :

public IEnumerable<Dog> GrowAll(this IEnumerable<Puppy> puppies)
{
    if(subjects == null)
        throw new ArgumentNullException("subjects");

    return GrowAllImpl(puppies);
}

private IEnumerable<Dog> GrowAllImpl(this IEnumerable<Puppy> puppies)
{
    foreach(var puppy in puppies)
        yield return puppy.Grow();
}
+3

All Articles