为什么调试和测试会跳过返回 IEnumerable的方法?在 C# 中?
最近,我用下面的代码尝试了很多次 xUnit 测试,但都失败了:
// testing target
IEnumerable<T> Foo(int n)
{
if(n==0) throw new AnException();
foreach(var item in ..)
{
yield return item;
{
yield break;
}
// test Method
void action() => Foo(0) ;
Assert.Throw<AnException>(action);
所以,我决定通过在 VS 中设置断点并在另一个沙箱项目(控制台应用程序)中调用它来调试 Foo 方法,该项目只调用该方法。
但是,控制流不会进入方法作用域,只是结束执行。
因此,我更改了代码,如下所示:
// test Method
void action ()
{
foreach(var item in Foo(0) ) {}// literally empty code inside loop.
}
Assert.Throw<AnException>(action);
该更改也确实适用于调试和测试。
你能告诉我是什么造成了这种差异吗?
Recently, I tried and failed so many times with xUnit test with the below code :
// testing target
IEnumerable<T> Foo(int n)
{
if(n==0) throw new AnException();
foreach(var item in ..)
{
yield return item;
{
yield break;
}
// test Method
void action() => Foo(0) ;
Assert.Throw<AnException>(action);
So, I decided to debug Foo method by setting break points in VS and calling it in another sandbox project(console app), which just calls the method.
However, the control flow wouldn't enter into the method scope and just ended its execution.
So, I changed my code as below:
// test Method
void action ()
{
foreach(var item in Foo(0) ) {}// literally empty code inside loop.
}
Assert.Throw<AnException>(action);
That change really works with debug and test as well.
Can you tell me what made that difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对
Foo(0)
的调用如void action() =>; Foo(0);
不消耗(读作:循环)IEnumerable
。您可以使用
Linq
方法之一来执行此操作,例如任何
。您需要包含
System.Linq
命名空间。代码如下所示。
That call to
Foo(0)
as invoid action() => Foo(0);
is not consuming (read as: looping over) theIEnumerable
.You can use one of the
Linq
methods to do so, e.g.Any
.You'll need to include the
System.Linq
namespace.The code then looks like below.