gpt4 book ai didi

C#、NUnit : How to deal with testing of exceptions and deferred execution

转载 作者:太空狗 更新时间:2023-10-29 23:35:30 24 4
gpt4 key购买 nike

假设我们有一个看起来像这样的方法:

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

foreach(var puppy in puppies)
yield return puppy.Grow();
}

如果我通过这样做来测试:

Puppy[] puppies = null;
Assert.Throws<ArgumentNullException>(() => puppies.GrowAll());

测试将失败说它

Expected: <System.ArgumentNullException>
But was: null

我可以通过将测试更改为

来解决这个问题
Puppy[] puppies = null;
Assert.Throws<ArgumentNullException>(() => puppies.GrowAll().ToArray());

这就是您通常的做法吗?还是有更好的方法来编写测试?或者也许是编写方法本身的更好方法?


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

最佳答案

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

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();
}

关于C#、NUnit : How to deal with testing of exceptions and deferred execution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2041998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com