Assert IEnumerables

前端 未结 4 1509
死守一世寂寞
死守一世寂寞 2021-02-18 19:10

As unit testing is not used in our firm, I\'m teaching myself to unit test my own code. I\'m using the standard .net test framework for some really basic unit testing.

A

相关标签:
4条回答
  • 2021-02-18 19:49

    I have an example of this I used for my "Implementing LINQ to Objects in 60 minutes" talk.

    It also in my MoreLinq project. Having tried to c'n'p it in here, it wraps horribly. Just grab from Github...

    0 讨论(0)
  • 2021-02-18 19:57

    There is a simple but not obvious way to do this with NUnit 3+ 'constraint' assertions:

    Assert.That(result, Is.EqualTo(expected).AsCollection, "My failure message");
    

    This will give you the same as the linq mentioned in other answers:

    Assert.That(result.SequenceEqual(expected), "My failure message");
    

    But the AsCollection version will tell you where the first difference is, and if the lengths are different.

    See https://docs.nunit.org/articles/nunit/writing-tests/constraints/EqualConstraint.html#comparing-arrays-collections-and-ienumerables

    0 讨论(0)
  • 2021-02-18 19:59

    You want the SequenceEqual() extension method (LINQ):

        string[] x = { "abc", "def", "ghi" };
        List<string> y = new List<string>() { "abc", "def", "ghi" };
    
        bool isTrue = x.SequenceEqual(y);
    

    or just:

       bool isTrue = x.SequenceEqual(new[] {"abc","def","ghi"});
    

    (it will return false if they are different lengths, or any item is different)

    0 讨论(0)
  • 2021-02-18 20:00

    I don't know which "standard .net test framework" you're referring to, but if it's Visual Studio Team System Unit testing stuff you could use CollectionAssert.

    Your test would be like this:

    CollectionAssert.AreEqual(ExpectedList, ActualList, "...");
    

    Update: I forgot CollectionAssert needs an ICollection interface, so you'll have to call ActualList.ToList() to get it to compile. Returning the IEnumerable is a good thing, so don't change that just for the tests.

    0 讨论(0)
提交回复
热议问题