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

Svi*_*ish 5 c# nunit exception 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();
}
Run Code Online (Sandbox Code Playgroud)

如果我通过这样做测试:

Puppy[] puppies = null;
Assert.Throws<ArgumentNullException>(() => puppies.GrowAll());
Run Code Online (Sandbox Code Playgroud)

测试将失败说它

预期:<System.ArgumentNullException>
但是: null

我可以通过改变测试来解决这个问题

Puppy[] puppies = null;
Assert.Throws<ArgumentNullException>(() => puppies.GrowAll().ToArray());
Run Code Online (Sandbox Code Playgroud)

这通常是你通常会这样做的吗?或者有更好的方法来编写测试吗?或者也许是一种更好的方法来编写方法本身?


尝试使用内置Select方法做同样的ToArray事情,即使没有或类似的事情它也失败了,所以显然你可以做些什么......我只是不知道:p

Jon*_*eet 3

测试没问题,但你的代码不行。您应该通过将方法分成两半来使代码在调用后立即抛出异常:

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();
}
Run Code Online (Sandbox Code Playgroud)