Named Iterator and Exceptions

I am writing a method that should check some parameters, and if they are checked, return IEnumerable. For instance.

public static IEnumerable<double> GetEnum(int param) { if (!IsValidParameter(param)) { throw new Exception(); } while(true) { yield return 5.0; } } 

However, I believe that due to lazy evaluation, when I run my unit tests with bad parameters, but don't call any of IEnumerable methods, an exception is not thrown.

 [Test] [ExpectedException(typeof(Exception))] void Test() { var ie = GetEnum(bad_param); } 

I can fix things by creating IEnumerable in another function (say Foo) and then check the parameters in GetEnum and call Foo, but is there a solution without having to create multiple functions?

Greetings, Jurgen

+4
source share
3 answers

Due to how the iterator blocks are defined, you will need two methods for this:

 public static IEnumerable<double> GetEnum(int param) { if (!IsValidParameter(param)) { throw new Exception(); } return GetEnumCore(param); } private static IEnumerable<double> GetEnumCore(int param) { while(true) { yield return 5.0; } } 

Only an iterator block is GetEnumCore ( GetEnumCore ); GetEnum runs immediately, performing your checks.

+9
source

Perhaps you can just initiate an iteration using the right enumerator?

 [Test] [ExpectedException(typeof(Exception))] void Test() { var ie = GetEnum(bad_param); var en = ie.GetEnumerator(); en.MoveNext(); } 
+2
source

Until you start listing your method, it will never be called. You can try to list in your test:

 var ie = GetEnum(bad_param).First(); 
+2
source

All Articles