Last active
February 28, 2020 23:21
-
-
Save crmckenzie/0f8960452a9827d5d81d to your computer and use it in GitHub Desktop.
NUnit Collection Equivalence Extension Methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
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
Lets you write