Search code examples
javac#nunithamcrest

In nUnit, what is the equivalent to Hamcrest's Matchers.containsInAnyOrder(Matcher... matchers)?


I'd like to assert that an ICollection contains items that will satisfy a collection of Constraints. For Java Hamcrest, I would use Matchers.containsInAnyOrder(Matcher... matchers). That is for a given collection, each item of the collection would match one matcher in matchers.

I'm struggling to find an equivalent in nUnit 3. Does one exist?


Solution

  • Alright. I implemented a slick answer to this. The key is to create an IComparer that will compare the constraint and the object. It looks like this:

    /// <summary>
    /// A Comparer that's appropriate to use when wanting to match objects with expected constraints.
    /// </summary>
    /// <seealso cref="System.Collections.IComparer" />
    public class ConstraintComparator : IComparer
    {
        public int Compare(object x, object y)
        {
            var constraint = x as IConstraint;
    
            var matchResult = constraint.ApplyTo(y);
    
            return matchResult.IsSuccess ? 0 : -1;
        }
    }
    

    I can then do the following:

    Assert.That(actual, Is.EquivalentTo(constraints).Using(new ConstraintComparator()));