C#,NUnit:如何处理异常测试和延迟执行

C#,NUnit:如何处理异常测试和延迟执行,c#,exception,nunit,deferred-execution,C#,Exception,Nunit,Deferred Execution,假设我们有一个如下所示的方法: public IEnumerable<Dog> GrowAll(this IEnumerable<Puppy> puppies) { if(subjects == null) throw new ArgumentNullException("subjects"); foreach(var puppy in puppies) yield return puppy.Grow(); } 这就是你

假设我们有一个如下所示的方法:

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

    foreach(var puppy in puppies)
        yield return puppy.Grow();
}
这就是你通常的做法吗?还是有更好的方法编写测试?或者是编写方法本身的更好方法



尝试使用内置的
Select
方法执行相同的操作,但即使没有
ToArray
或类似的操作,它也失败了,因此显然您可以对此采取一些措施。。。我只是不知道是什么:测试很好-你的代码不是。您应该通过将方法一分为二,使代码在调用异常时立即抛出异常:

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();
}
public IEnumerable GrowAll(此IEnumerable小狗)
{
if(subjects==null)
抛出新的异常(“主题”);
返回生长样本(幼犬);
}
私人IEnumerable growlImpl(此IEnumerable小狗)
{
foreach(幼犬中的幼犬)
收益回报小狗。成长();
}

aaah,这就是为什么您的库中的所有方法看起来都是这样的。。。有道理!但我不确定我是否喜欢它。。。呵呵。我得说我更喜欢用一种方法。但是哦,好吧。我想过一会儿我就会习惯了:)这是迭代器块的一个不幸的副作用。完全明白。是的,我有点明白为什么会这样。只是不是推荐的处理方法:)
Puppy[] puppies = null;
Assert.Throws<ArgumentNullException>(() => puppies.GrowAll().ToArray());
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();
}