Search code examples
c#unit-testing

My unit test cannot cover yield return function


This is the class to test:

public class TestClass
{
    public IEnumerable<int> GetInt()
    {
        yield return 1;
        yield return 2;
        yield return 3;
        yield return 4;
        yield return 5;
    }
}

My simple unit test:

[Test]
public void TestYieldReturn()
{
    var test = new TestClass();
    var results = test.GetInt();
    Assert.AreEqual(1, results.Min());
    Assert.AreEqual(5, results.Max());
}

My test didn't cover this implementation, I ran it in debug mode but it didn't hit the breakpoint. Any suggestion?


Solution

  • You simply must materialize the list first because yield returns and enumerable, not an actual list.

    var results = test.GetInt().ToList();