Range Constraint
RangeConstraint tests that a value falls within an inclusive range. Both the lower and upper bounds are included in
the valid range.
Usage
Is.InRange(IComparable from, IComparable to)
Modifiers
.Using(IComparer comparer)
.Using<T>(IComparer<T> comparer)
.Using<T>(Comparison<T> comparer)
Examples
[Test]
public void RangeConstraint_Examples()
{
// Numeric ranges (inclusive)
Assert.That(5, Is.InRange(1, 10));
Assert.That(1, Is.InRange(1, 10)); // Lower bound is included
Assert.That(10, Is.InRange(1, 10)); // Upper bound is included
Assert.That(0, Is.Not.InRange(1, 10));
// DateTime ranges
var start = new DateTime(2024, 1, 1);
var end = new DateTime(2024, 12, 31);
Assert.That(new DateTime(2024, 6, 15), Is.InRange(start, end));
// String ranges (alphabetical comparison)
Assert.That("banana", Is.InRange("apple", "cherry"));
}
Notes
The range is inclusive on both ends:
Is.InRange(1, 10)passes for values 1, 10, and everything in between.frommust be less than or equal toto, otherwise the constraint throws anArgumentException. Negative bounds are fine, but the range must be written in increasing order: useIs.InRange(-10, 0), notIs.InRange(0, -10). If the bounds are computed and could end up in either order, sort them first:int lower = Math.Min(a, b); int upper = Math.Max(a, b); Assert.That(actual, Is.InRange(lower, upper));For exclusive bounds, combine
Is.GreaterThanandIs.LessThanwithAnd:Assert.That(5, Is.GreaterThan(1).And.LessThan(10)); // Exclusive boundsRangeConstrainthas noWithinmodifier. To allow for imprecision, widen the bounds, or combineIs.GreaterThanandIs.LessThanwith their own tolerances.