为什么调试和测试会跳过返回 IEnumerable的方法?在 C# 中?

发布于 2025-01-11 10:57:29 字数 675 浏览 3 评论 0原文

最近,我用下面的代码尝试了很多次 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千柳 2025-01-18 10:57:29

Foo(0) 的调用如 void action() =>; Foo(0); 不消耗(读作:循环)IEnumerable
您可以使用 Linq 方法之一来执行此操作,例如 任何

您需要包含 System.Linq 命名空间。
代码如下所示。

void action() => Foo(0).Any();

That call to Foo(0) as in void action() => Foo(0); is not consuming (read as: looping over) the IEnumerable.
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.

void action() => Foo(0).Any();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文