ComparisonConstraint
Abstract base class for constraints that compare values to
determine if one is greater than, equal to or less than
the other.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace NUnit.Framework.Constraints
{
[NullableContext(1)]
[Nullable(0)]
public abstract class ComparisonConstraint : Constraint
{
private readonly object _expected;
private readonly string _comparisonText;
[Nullable(2)]
private string _description;
private Tolerance _tolerance = Tolerance.Default;
private ComparisonAdapter _comparer = ComparisonAdapter.Default;
public override string Description {
get {
if (_description == null)
_description = DefaultDescription(_comparisonText);
return _description;
}
}
public ComparisonConstraint Percent {
get {
_tolerance = _tolerance.Percent;
return this;
}
}
protected ComparisonConstraint(object expected, string comparisonText)
: base(expected)
{
Guard.ArgumentValid(expected != null, "Cannot compare using a null reference.", "_expected");
_expected = expected;
_comparisonText = comparisonText;
}
public override ConstraintResult ApplyTo<[Nullable(2)] TActual>(TActual actual)
{
Guard.ArgumentValid(actual != null, "Cannot compare to a null reference.", "actual");
return new ConstraintResult(this, actual, PerformComparison(_comparer, actual, _expected, _tolerance));
}
protected abstract bool PerformComparison(ComparisonAdapter comparer, object actual, object expected, Tolerance tolerance);
public ComparisonConstraint Using(IComparer comparer)
{
_comparer = ComparisonAdapter.For(comparer);
return this;
}
public ComparisonConstraint Using<[Nullable(2)] T>(IComparer<T> comparer)
{
_comparer = ComparisonAdapter.For(comparer);
return this;
}
public ComparisonConstraint Using<[Nullable(2)] T>(Comparison<T> comparer)
{
_comparer = ComparisonAdapter.For(comparer);
return this;
}
public ComparisonConstraint Within(object amount)
{
if (!_tolerance.IsUnsetOrDefault)
throw new InvalidOperationException("Within modifier may appear only once in a constraint expression");
_tolerance = new Tolerance(amount);
return this;
}
private string DefaultDescription(string comparisonText)
{
if (comparisonText == null)
throw new ArgumentNullException("comparisonText", "Comparison text can not be null");
StringBuilder stringBuilder = new StringBuilder(comparisonText);
stringBuilder.Append(MsgUtils.FormatValue(_expected));
if (_tolerance != null && _tolerance.HasVariance) {
stringBuilder.Append(" within ");
stringBuilder.Append(MsgUtils.FormatValue(_tolerance.Amount));
if (_tolerance.Mode == ToleranceMode.Percent)
stringBuilder.Append(" percent");
}
return stringBuilder.ToString();
}
}
}