What's the idiomatic way to verify collection size in xUnit?

前端 未结 5 572
遥遥无期
遥遥无期 2021-02-06 20:25

I have in my test suite a test that goes something like this:

[Fact]
public void VerifySomeStuff()
{
    var stuffCollection = GetSomeStuff();

    Assert.Equal(         


        
相关标签:
5条回答
  • 2021-02-06 20:25

    Xunit offers quick fixes for most of its warnings, so you should be able to see what it thinks is "right".

    In your case, it wants you to use Assert.Single since you are expecting exactly one item. If you were asserting an arbitrary number, like 412, then it would not give you a warning about using Count. It will only suggest using Single if you are expecting one item, or Empty if you are expecting no items.

    0 讨论(0)
  • 2021-02-06 20:32

    I found this give me the same error:

    Assert.Equal(2, vm.Errors.Count());
    

    And casting it stopped the error from appearing.

    Assert.Equal(2, (int)vm.Errors.Count());
    
    0 讨论(0)
  • 2021-02-06 20:35

    I had same issue when I used Count property as below in xUnit.

    After, I use Count() function on collection, it fixed my issue.

    0 讨论(0)
  • 2021-02-06 20:37

    For single element in a list, it's best to use this instead: Assert.Single(resultList);

    0 讨论(0)
  • 2021-02-06 20:41

    If you have more than one item, you can't use Assert.Single.

    The expectation seems to be that you should use Assert.Collection:

    var stuffCollection = GetSomeStuff();
    
    Assert.Collection(stuffCollection, 
        item => true, // this lambda verifies the first item
        item => true, // second item
    );
    

    The assertion above verifies that there are exactly two items in the collection. You can provide stricter lambdas (such as item => item.property1 == 7) for each item if you want.

    Personally, I'm not a fan; this seems like a very verbose way of saying how long you want the collection to be.

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