views:

89

answers:

1

My unit tests are doing something very strange when I call a method of a generic base type. I have tried both NUnit and MSTest with the same result. This is how the code is organized:

public class MyStub {}

public class EnumerableGenerator
{
     public bool GotMyStubs;

     public IEnumerable<MyStub> GetMyStubs()
     {
         GotMyStubs = true;
         yield return new MyStub();
     }
}
public class ConsoleRunner
{
public void Main(string args[])
{
     EnumerableGenerator gen = new EnumerableGenerator();
     gen.GotMyStubs = false;
     var myStubs = gen.GetMyStubs();
     if  (!gen.GotMyStubs)
         return 1;
} 
}

The test fails obviously. The strange part is that the code functions fine when I'm integration testing it. It only breaks in the unit test. I cannot step into GetMyStubs at all. Break points within the method do not break either. I have turned on breaking for all exceptions being thrown by the CLR and this yields nothing as well.

I examined the type returned by GetMyStubs and the type's full name looks like this:

[MyNamespace.EnumerableGenerator2+<GetMyStubs>d__8[[MyNamespace.MyStub, MyNamespace, Version=7.1.0.0, Culture=neutral, PublicKeyToken=null]]

Now when I look at my code coverage numbers (through MSTest) I notice that there is a EnumerableGenerator.d__8 entry.

Has anyone seen something like this? I'm completely lost....

+2  A: 

The code you've given won't even compile - there isn't a Count property on IEnumerable<T>. There's a Count() extension method - is that what you meant?

I strongly suspect that MyMethod() doesn't really look like that either. I suspect it actually uses yield return to return the items... at which point the type's full name would make sense, as it's a state machine generated for you by the iterator block.

Assuming that's the case, when you call MyMethod(), that won't execute any of your code. It will create the state machine and return it. When you start iterating over it, then it will start executing your code... and that's when I'd expect break points to be hit.

Could you provide a short but complete example (using NUnit if necessary, but a console app would be ideal) of it failing?

Jon Skeet
Yup you were right about the extension method. That is what I meant. And again you were right about the yield return. I've definitely learned something about that today. I'll update the example above to more clearly illustrate the code.
Adam Driscoll