【问题标题】:Assertion for check string value include array of string检查字符串值的断言包括字符串数组
【发布时间】:2022-05-27 00:16:36
【问题描述】:

我创建了如下的书类

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"}
]

我想断言应该是真的,如果 Books List 中的 bookName 可以在 string[] expectResults {"apple", "ap"} 中找到 只是下面的例子

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

但它总是失败,任何人都可以建议如何做到这一点?

谢谢

【问题讨论】:

    标签: c# linq fluent-assertions


    【解决方案1】:

    如果我理解正确,那么您可以为此使用扩展方法。使用Assert 方法创建一个类,如下所示:

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

    这可以(应该!)通过在 Assert 方法中检查一个空的书单和/或空的预期结果来改进。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 谢谢,但我想断言,如果expectedresults是{“apple”,“apps”},它需要返回true,因为每条bookname记录都包含expectedresult
      • 结果不清楚你想看到什么。请根据提供的数据提供结果示例
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2019-11-12
      • 2020-11-28
      • 2011-02-24
      • 2019-03-15
      • 1970-01-01
      相关资源
      最近更新 更多