0

I have a collection:

new[] { new { A = 5, PropIDontCareAbout = "XXX" }, new { A = 7, PropIDontCareAbout = "XXX" }, new { A = 9, PropIDontCareAbout = "XXX" } }

I want to check that it at least contains both new { A = 9 } and new { A = 5 } in any order.

I can use ContainEquivalentOf, but I have to do it one-by-one:

var actual = new[] { 
  new { A = 5, PropIDontCareAbout = "XXX" }, 
  new { A = 7, PropIDontCareAbout = "XXX" }, 
  new { A = 9, PropIDontCareAbout = "XXX" } 
};
var expected = new [] { new { A = 5 }, new { A = 9 } };
foreach (var expectedItem in expected) {
    actual.Should().ContainEquivalentOf(expectedItem);
}

Update: I can't use Contains because it requires actual and expected objects to have the same type.

THX-1138
  • 21,316
  • 26
  • 96
  • 160

1 Answers1

1

I do not see an explicit solution. You can work-around using Select to create subject in the format of the expectation, then you can use Contains(IEnumerable<T> expected, ...):

var actual = new[] { 
    new { A = 1, PropIDontCareAbout = "XXX" }, 
    new { A = 7, PropIDontCareAbout = "XXX" }, 
    new { A = 9, PropIDontCareAbout = "XXX" } 
};

actual.Select(x => new { x.A }).Should()
    .Contain(new[] { new { A = 9 }, new { A = 5 } });

In case of one the elements is not in the list you get a message like that:

Expected collection {{ A = 1 }, { A = 7 }, { A = 9 }}
to contain {{ A = 9 }, { A = 5 }},
but could not find {{ A = 5 }}.
lg2de
  • 616
  • 4
  • 16
  • @thx-1138, would be great to get feedback for my answer! – lg2de Jul 11 '22 at 13:08
  • apologies for the late response. Your solution does not work because `Contain` does an exact match while I need `Equivalent` comparison that does partial object matching. I will update my question. – THX-1138 Jul 15 '22 at 14:01
  • 1
    You are right, @THX-1138. I've updated my answer with a work-around. – lg2de Jul 17 '22 at 12:20