Search code examples
c#linqfluent-assertions

Assertion for check string value include array of string


I create the class of book as below

public class book
{
   public int id {get;set;}
   public string bookName {get;set;}
}

I define the list of book data : List<book> books as

[
{"id":1,"bookName":"falling apple"},{"id":2,"bookName":"fall app"},{"id":3,"bookName":"fall apples"}
]

I want to make assertion should be true , if bookName in List of Books can find in string[] expectResults {"apple", "ap"} Just the below example

books.should().match(m=>m.any(expectResults.contains(m.bookName)))

But it always failure, can anyone advise how to do it ?

Thank you


Solution

  • If I understand correctly then you could use an extension method for this. Create a class with an Assert method in like this:

    public static class Assertion
    {
        public static bool Assert(this List<Book> books, IEnumerable<string> expectedResults)
        {
            books = expectedResults.Aggregate(books, (current, expectedResult) => current.Where(b => !b.BookName.Contains(expectedResult)).ToList());
            return books.Count == 0;
        }
    }
    

    You can test this from a console app like this:

    private static void Main()
    {
        var books = new List<Book>
        {
            new Book { Id = 1, BookName = "falling apple" },
            new Book { Id = 2, BookName = "fall app" },
            new Book { Id = 3, BookName = "fall apples" }
        };
    
        var expectedResults = new[] { "apple", "ap" };
    
        Console.WriteLine(books.Assert(expectedResults)
            ? "All expected results found."
            : "Some expected results not found.");
    }
    

    This could (should!) be improved by checking in the Assert method for an empty book list and/or empty expected results.