Skip to content

IEnumerable gets evaluated multiple times when using BeEmpty() #2490

@Shidairyu

Description

@Shidairyu

Description

There seems to be an issue with BeEmpty() when used with IEnumerable. The IEnumerable gets evaluated multiple times, leading to unexpected behavior.

Reproduction Steps

private bool a = false;

public IEnumerable<string> Get()
{
    if (a)
    {
        yield break;
    }

    a = true;
    yield return "123";
}

[TestMethod]
public void Execute()
{
    var result = Get();

    result.Should().BeEmpty();
}

Expected behavior

I expect the test to fail, with the message: "Expected result to be empty, but found {"123"}."

Actual behavior

Test fails, but with the message: "Expected result to be empty, but found {empty}."

Regression?

No response

Known Workarounds

Converting the IEnumerable to a list before asserting solves the issue:

[TestMethod]
public void Execute()
{
    var result = Get().ToList();

    result.Should().BeEmpty();
}

Configuration

FluentAssertions version: 6.12.0
.NET version: 7.0

Other information

The issue seems to arise from how Fluent Assertions handles the evaluation of IEnumerable. Ensuring the collection is evaluated only once before the emptiness check might resolve this issue.

Are you willing to help with a pull-request?

No

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions