1

I have a class with collection class inside

public class SearchResult {
        public int Id { get; set; }
        public int Total { get; set; }
        public IEnumerable<Book> Books { get; set; }
}

public class Book {
        public int BookId { get; set; }
        public string BookName { get; set; }
        public string Publisher { get; set; }
        public string ISBNCode { get; set; }
        public IList<catagory> Catagories { get; set; }
}

I have a question , if I create the other object , with same structure of SearchResult and I want to copy SearchResult to SearchResultClone, which inside Books only copy BookId and BookName remain is empty. Just like below

{
  "Id": 0,
  "Total": 3,
  "Books": [
    {
      "BookId": 1,
      "BookName": "Book A",
      "Publisher": "",
      "ISBNCode": "",
      "Catagories": []
    },
    {
      "BookId": 2,
      "BookName": "Book B",
      "Publisher": "",
      "ISBNCode": "",
      "Catagories": []
    },
    {
      "BookId": 3,
      "BookName": "Book C",
      "Publisher": "",
      "ISBNCode": "",
      "Catagories": []
    }
  ]
}

Event the original result have value of Publisher, ISBNCode ..etc How to do it in LINQ ?

My second question is , if I want to make a fluent assertions as above object

var result = await sut.search(query);
result.Should().BeEquivalentTo ({the SearchResultClone }) 

How to write this fluent assertion ?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Jack Man
  • 19
  • 3

2 Answers2

0

You need to create new instances of the classes based on the old instances:

var ans = result.Select(sr => new SearchResult {
    Id = sr.Id,
    Total = sr.Total,
    Books = sr.Books.Select(b => new Book { BookId = b.BookId, BookName = b.BookName }).ToList()
}).ToList();
NetMage
  • 26,163
  • 3
  • 34
  • 55
  • I have success to do this by var result = await sut.search(query); result.Should().BeEquivalentTo (expected) so I don't need to mapping on each one Thank you for your help – Jack Man Mar 02 '22 at 10:10
0
result.Should().BeEquivalentTo ({the SearchResultClone }) 

How to write this fluent assertion ?

If your expectation (the object you pass into BeEquivalentTo) is of the type SearchResult, then FA will try to compare the empty values of ISBN to the same property on the sut. You can solve that by doing something like:

sut.Should().BeEquivalentTo(new 
{
  Id = "some value",
  Total = 123,
  Books = new[] 
  {
    new 
    {
      BookId = 123,
      BookName = "some book"
    }
  }
});
Dennis Doomen
  • 8,368
  • 1
  • 32
  • 44