Why debug and test skips over a method returning IEnumerable<t> in C#?

Viewed 50

Recently, I tried and failed so many times with xUnit test with the below code :

// testing target
IEnumerable<T> Foo(int n) 
{
    if(n==0) throw new AnException();

    foreach(var item in ..)
    {
        yield return item;
    {
    yield break;
}

// test Method

void action() => Foo(0) ;
Assert.Throw<AnException>(action);

So, I decided to debug Foo method by setting break points in VS and calling it in another sandbox project(console app), which just calls the method.

However, the control flow wouldn't enter into the method scope and just ended its execution.

So, I changed my code as below:


// test Method
void action ()
{
    foreach(var item in Foo(0) ) {}// literally empty code inside loop.
}
Assert.Throw<AnException>(action);

That change really works with debug and test as well.

Can you tell me what made that difference?

1 Answers

That call to Foo(0) as in void action() => Foo(0); is not consuming (read as: looping over) the IEnumerable.
You can use one of the Linq methods to do so, e.g. Any.

You'll need to include the System.Linq namespace.
The code then looks like below.

void action() => Foo(0).Any();
Related