Home > Software design >  How to check the order of a nested collection with FluentAssertions
How to check the order of a nested collection with FluentAssertions

Time:09-21

I am trying to check the order of a nested collection with FluentAssertion as follows.

selectedStudent.MarkSheets.Select(x => x.Comments.Should().BeInDescendingOrder(x => x.CommentedTime));

But this seems to be not correct since even if I check BeInAscendingOrder(x => x.CommentedTime the assertion is true. How can I test this correctly using FluentAssertion?

CodePudding user response:

You can use AllSatisfy.

record Comment(DateTime CommentedTime);
record MarkSheet(List<Comment> Comments);
record Student(List<MarkSheet> MarkSheets);
var selectedStudent = new Student(new List<MarkSheet>()
{
    new MarkSheet(new List<Comment>()
    {
        new Comment(new DateTime(2022, 01, 01)),
        new Comment(new DateTime(2023, 01, 01))
    }),
    new MarkSheet(new List<Comment>()
    {
        new Comment(new DateTime(2023, 01, 01)),
        new Comment(new DateTime(2024, 01, 01))
    })
});

selectedStudent.MarkSheets.Should().AllSatisfy(x => 
    x.Comments.Should().BeInDescendingOrder(x => x.CommentedTime));

Properly fails with

Expected selectedStudent.MarkSheets to contain only items satisfying the inspector:
    At index 0:
        Expected x.Comments {Comment { CommentedTime = 01/01/2022 00.00.00 }, Comment { CommentedTime = 01/01/2023 00.00.00 }} to be ordered "by CommentedTime" and result in {Comment { CommentedTime = 01/01/2023 00.00.00 }, Comment { CommentedTime = 01/01/2022 00.00.00 }}
    At index 1:
        Expected x.Comments {Comment { CommentedTime = 01/01/2023 00.00.00 }, Comment { CommentedTime = 01/01/2024 00.00.00 }} to be ordered "by CommentedTime" and result in {Comment { CommentedTime = 01/01/2024 00.00.00 }, Comment { CommentedTime = 01/01/2023 00.00.00 }}
  • Related