Skip to content

Instantly share code, notes, and snippets.

@crmckenzie
Last active February 28, 2020 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crmckenzie/0f8960452a9827d5d81d to your computer and use it in GitHub Desktop.
Save crmckenzie/0f8960452a9827d5d81d to your computer and use it in GitHub Desktop.
NUnit Collection Equivalence Extension Methods
public static class NUnitExtensions
{
public static CollectionItemsEqualConstraint Using<T>(this CollectionEquivalentConstraint constraint,
Func<T, T, bool> expression)
{
return constraint.Using(new PredicateComparison<T>(expression));
}
public static CollectionItemsEqualConstraint Using<TExpected, TActual>(this CollectionEquivalentConstraint constraint,
Func<TExpected, TActual, bool> expression)
{
return constraint.Using(new PredicateComparison<TExpected, TActual>(expression));
}
}
public class PredicateComparison<T> : IComparer<T>
{
private readonly Func<T, T, bool> _comparison;
public int Compare(T x, T y)
{
if (_comparison.Invoke(x, y))
{
return 0;
}
return -1;
}
public PredicateComparison(Func<T, T, bool> comparison)
{
_comparison = comparison;
}
}
public class PredicateComparison<TExpected, TActual> : IComparer
{
private readonly Func<TExpected, TActual, bool> _func;
public int Compare(object x, object y)
{
var expected = (TExpected)x;
var actual = (TActual)y;
if (_func(expected, actual))
return 0;
return -1;
}
public PredicateComparison(Func<TExpected, TActual, bool> func)
{
_func = func;
}
}
@crmckenzie
Copy link
Author

Lets you write

Assert.That(actualCollection, Is.EquivalentTo(expectedCollection)
    .Using<T>((x, y) => x.Id == y.Id));

@StephenWithPH
Copy link

Or: Assert.That(actualCollection, Is.EquivalentTo(expectedCollection)
.Using<TExpected, TActual>((x, y) => x.Id == y.SomeOtherProperty));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment