检查字符串值的断言包括字符串数组

Assertion for check string value include array of string

我创建的class书如下

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

我定义图书数据列表:List<book> books

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

如果图书列表中的 bookName 可以在 string[] expectResults {"apple", "ap"} 中找到,我想断言应该为真 就是下面的例子

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

但总是失败,谁能告诉我怎么做?

谢谢

你必须应用相反的想法。因为你需要匹配部分列表 检查示例。我只用苹果来搭配

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; }
}

如果我没理解错的话,你可以使用扩展方法。使用 Assert 方法创建一个 class,如下所示:

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;
    }
}

您可以像这样从控制台应用程序对此进行测试:

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.");
}

这可以(应该!)通过检查空书列表的断言方法来改进and/or 空预期结果。