ComparisonAdapter
ComparisonAdapter class centralizes all comparisons of
values in NUnit, adapting to the use of any provided
IComparer, IComparer<T>
or Comparison<T>.
using NUnit.Framework.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
namespace NUnit.Framework.Constraints
{
public abstract class ComparisonAdapter
{
private class DefaultComparisonAdapter : ComparerAdapter
{
public DefaultComparisonAdapter()
: base(NUnitComparer.Default)
{
}
}
private class ComparerAdapter : ComparisonAdapter
{
private readonly IComparer comparer;
public ComparerAdapter(IComparer comparer)
{
this.comparer = comparer;
}
public override int Compare(object expected, object actual)
{
return comparer.Compare(expected, actual);
}
}
private class ComparerAdapter<T> : ComparisonAdapter
{
private readonly IComparer<T> comparer;
public ComparerAdapter(IComparer<T> comparer)
{
this.comparer = comparer;
}
public override int Compare(object expected, object actual)
{
if (!TypeHelper.TryCast<T>(expected, out T value))
throw new ArgumentException(string.Format("Cannot compare {0}", expected?.ToString() ?? "null"));
if (!TypeHelper.TryCast<T>(actual, out T value2))
throw new ArgumentException(string.Format("Cannot compare to {0}", actual?.ToString() ?? "null"));
return comparer.Compare(value, value2);
}
}
private class ComparisonAdapterForComparison<T> : ComparisonAdapter
{
private readonly Comparison<T> comparison;
public ComparisonAdapterForComparison(Comparison<T> comparer)
{
comparison = comparer;
}
public override int Compare(object expected, object actual)
{
if (!TypeHelper.TryCast<T>(expected, out T _))
throw new ArgumentException(string.Format("Cannot compare {0}", expected?.ToString() ?? "null"));
if (!TypeHelper.TryCast<T>(actual, out T _))
throw new ArgumentException(string.Format("Cannot compare to {0}", actual?.ToString() ?? "null"));
return comparison((T)expected, (T)actual);
}
}
public static ComparisonAdapter Default => new DefaultComparisonAdapter();
public static ComparisonAdapter For(IComparer comparer)
{
return new ComparerAdapter(comparer);
}
public static ComparisonAdapter For<T>(IComparer<T> comparer)
{
return new ComparerAdapter<T>(comparer);
}
public static ComparisonAdapter For<T>(Comparison<T> comparer)
{
return new ComparisonAdapterForComparison<T>(comparer);
}
public abstract int Compare(object expected, object actual);
}
}