Home > Net >  Assertion for check string value include array of string
Assertion for check string value include array of string

Time:05-27

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

CodePudding user response:

you have to appy reversed idea. sonce you need to match a partial list check example. i made with only apple to match

void Main()
{
    string json = "[{\"id\":1,\"bookName\":\"falling apple\"},{\"id\":2,\"bookName\":\"fall app\"},{\"id\":3,\"bookName\":\"fall apples\"}]";
    var obj = JsonConvert.DeserializeObject<List<book>>(json);
    List<string> expectResults = new List<string>() { "apple"};
    var result = new List<book>();
    obj.ForEach(fe =>
    {
        expectResults.ForEach(fee => {
            if(fe.bookName.Contains(fee))
                result.Add(fe);
        });
    });
    
    Console.Write(result);
    
}

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

enter image description here

CodePudding user response:

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.

  • Related